Wednesday, April 20, 2011

Linq query to include a subtype

In my model I have Address as a base class and MailingAddress, Email, and Phone as subclasses of Address. A Person has an address so query to get a person who has an Oakland Mailing address would look like this:

var peopleInOakland = from p in entities.DbObjectSet.OfType<Person>()
                             from a in p.Addresses.OfType<MailingAddress>()
                             where a.City == "Oakland"
                             select p;

How do I also include the mailing addresses of the person in my query result? I know I should be using an Include, but I'm unsure of how to name the MailingAddress in the .Include argument.

Thanks in advance

From stackoverflow
  • Just select into an anonymous type using the comprehension expression's local name:

    ...
    select new {
      Persion = p,
      Address = a
    };
    
    Richard : Would be nice to know why this is down-voted.
    Jonathan : I think he's asking for the syntax to populate the Person objects that are returned with the Addresses which are of type MailingAddress. That said, I don't know how to do that off the top of my head :)
    Richard : @Jonathan: if correct, then that is a trivial modification of either answer, but need clarification; as both answers do "include the mailing addresses[...]in the query result"
  • You will have to create a new type that has the specific type that you are looking for, like so:

    var peopleInOakland = from p in entities.DbObjectSet.OfType<Person>()
        from a in p.Addresses.OfType<MailingAddress>()
        where a.City == "Oakland"
        select 
            new { Person = p, Addresses = p.Addresses.OfType<MailingAddress>() };
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.