Ralph Shillington
Ralph Shillington

Reputation: 21108

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

Upvotes: 2

Views: 1327

Answers (2)

casperOne
casperOne

Reputation: 74550

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>() };

Upvotes: 2

Richard
Richard

Reputation: 109100

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

...
select new {
  Persion = p,
  Address = a
};

Upvotes: 0

Related Questions