How can you dynamically retrieve all records of a particular subtype with Linq in Entities?

I am trying to get a list of all the objects in a database of the specified type. I did this before when the type was known at compile time, but now I am trying to pass the type to the method and return the method to all the records of this specified type, and I cannot get it to work. I tried the following:

public IList<WritingObject> GetBasicObjectsByProject(int projectId, Type oType) { var results = from o in _objects.AsQueryable where o.Project.Id == projectId && o.GetType() == oType select o; return results.ToList<WritingObject>(); } 

This did not work because Linq to Entities does not support the GetType () method. Then i tried

  var results = from o in _objects.AsQueryable where o.Project.Id == projectId && o is oType select o; 

This does not work because the compiler claims that oType does not have a known type. Using typeof(oType) causes the same error as executing OfType<oType>() on IQueryable .

I'm running out of ideas to preserve this dynamic without breaking it down into one method for each subtype. Does anyone have any ideas?

+4
source share
2 answers

Sort of:?

 var query = from o in _objects.AsQueryable() where o.Project.Id == projectId select o; var ofType = typeof (Queryable).GetMethod("OfType").MakeGenericMethod(oType); var list = (IQueryable)ofType.Invoke( null, new object[] {query}).Cast<WritingObject>().ToList(); 

Please note that this also applies to other subtypes.

+1
source

I think the problem here is that Linq-to-Entities is trying to translate o.GetType into SQL, which obviously cannot. After reading the question again, I realized that this is due to linq with objects that cannot match the CLR type to the database type. Linq to Entities help talks about this:

The standard LINQ query operators that deal with CLR type conversion and testing are supported in the Entity Framework. Only CLR types that map to conceptual model types are supported in LINQ to Entities. For a list of conceptual model types, see Conceptual Model Types .

The foregoing means that it can only convert a few supported CLR types to the corresponding EDM types as part of query generation. If the type you are trying to use is not in this list, you will need to filter the type after receiving the query result.

The solution to this problem may be ineffective - you will need to request all the records that match the projectId criteria, and then filter them by type:

  var results = (from o in _objects.AsQueryable where o.Project.Id == projectId select o).ToList(); //force query execution here results = from o in results where o.GetType() == oType select o; return results.ToList<WritingObject>(); 
0
source

All Articles