简体   繁体   中英

Entity Framework exclude records from the foreign table

I'm having a problem excluding the records from a foreign table based on a condition.

// this query returns everything from all the tables that are referenced in MainTable

    var query = db.MainTable.Where(x => x.ID == 123)

How can I exclude some of the records from one of the foreign tables based on a Status field in the foreign table? Something like this:

    var query = db.MainTable.Where(x => x.ID == 123 && y => y.ForeignTable.Status == false)

Thank you.

Since you said that you do have the correct relationships set up, and your example seems to suggest that what you have is a singular relationship (not a reference to an ICollection) you should be able to just do:

var query = db.MainTable.Where(x => x.ID == 123 && x.ForeignTable.Status == false) .

If you were using an ICollection, you'd then have to do something like this:

var query = db.MainTable.Where(x => x.ID == 123 && x.ForeignTable.All(y => y.Status == false))

which I think would work, but haven't tested.

You could also look into the Enumerable.Join syntax which I have needed for some more complex joins. It can be really verbose however, and for simple joins the method above should work just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM