Is there a way to create an association in entity framework that always applies a “where” filter?
Here’s an example:
Suppose that I have a database that uses “soft” deletes — so there is a “deleted” column in every table.
So if I have a Customer entity that is related to Address (1:0..n), I would like for the Addresses navigation property to always be filtered on the deleted flag, so that if I go Customer.Addresses, the collection will only return Addresses where deleted == 0.
Anyone know of some way to do that?
No, there isn’t.
Same reason you can’t have a conditional foreign key.
A workaround could be to use TPH on the Address table:
So when you do
ctx.Customer.Include("AddressDeleted").Single()it will only return the addresses that are flagged as deleted.Or you could defined an association to Address, and use
ctx.Customer.Addresses.OfType<AddressDeleted>().Does that solve your problem?