Chris Dellinger
Chris Dellinger

Reputation: 2352

Filtering a query in Entity Framework based upon a child value

I've got a model set up in the Entity Framework (EF) where there are two tables, parent and child, in a one to many relationship. Where I am having trouble is writing a query with linq where I am trying to retrieve a single instance of the parent while filtering upon a field in the parent and another field in the child. It would look something like what is listed below:

var query = from c in context.ParentTable 
            where c.IsActive == true && c.ChildTable.Name = "abc" 
            select c;

Unfortunately when I try this it fails because no field named "Name" appears available via Intellisense when I type c.ChildTable.

Any guidance would be appreciated.

Upvotes: 1

Views: 1697

Answers (1)

Morteza Manavi
Morteza Manavi

Reputation: 33206

That is correct because c.ChildTable is not of your Child type but EntityCollection<Child>. In order to make your query work, you need to modify it like this:

var query = from p in context.ParentTable 
            from c in p.ChildTable 
            where p.IsActive == true 
                  && c.Name == "abc" 
            select p;

Upvotes: 3

Related Questions