I am trying to get a list of all objects in the database of a specified type. I have done this before when the type was known at compile time, but now I am trying to pass a type into the method and have the method return all the records of that specified type, and I can't get it working. I have 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 didn't work because Linq to Entities doesn't support the GetType() method. Next I tried
var results = from o in _objects.AsQueryable
where o.Project.Id == projectId
&& o is oType
select o;
This doesn't work because the compiler claims that oType is not of a known type. Using typeof(oType)
produces the same error, as does performing OfType<oType>()
on the IQueryable
.
I'm running out of ideas to keep this dynamic without splitting it out into one method per sub-type. Does anyone have any ideas?