Entity Framework: how to return a base type from L2E
-
01-07-2019 - |
Question
Considering the following architecture:
- a base object 'Entity'
- a derived object 'Entry:Base'
- and a further derived object 'CancelledEntry:Entry'
In EntitySQL I can write the following:
[...] where it is of (only MyEntities.Entry) [...]
to return only objects of type Entry and no Entity or CancelledEntry.
In linq to sql, the following command will return objects of type Entry and CancelledEntry.
EntityContext.EntitySet.OfType<Entry>()
What is the syntax/function to use to return only objects of type Entry?
Solution
Why don't you apply an extension method on IQueryable< Entry > called ApplyBaseEntryFilter() which would apply this filter and return an IQueryable< Entry >.
This is an example of how to reuse linq query fragments. Using extension methods on IQueryable< Entity > is a great way to re-use queries as you should neve rneed to copy and paste query fragments around your application, hope that helps.
OTHER TIPS
Ok, I have found a partial solution:
EntityContext.EntitySet.OfType<Entry>().Where( obj => !(obj is CancelledEntry) )
This is quite awful however, since if I create a new derived object, I have to go in all the queries and specifically add a condition to remove it.
There has to be a better solution