Reputation: 219
I am trying to use generics to load a record into my dbcontext cache. I am using the following code.
_Context.Set<T>().Where(R => (int)R.GetType().GetProperty("Id").GetValue(R) == id).Load();
This code is throwing the following error and I cannot seem to figure out how to get around it.
System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object)' method, and this method cannot be translated into a store expression.
Is what I am doing possible or is there another way.
Upvotes: 0
Views: 489
Reputation: 3289
The problem is that you're attempting to use Reflection methods (GetType()
, GetProperty()
, GetValue()
) with LINQ to Entities, and it doesn't understand them. The methods you're allowed to use inside a LINQ query are limited to what the query provider supports, and in the case of LINQ to Entities it's mostly things that can be translated into SQL relatively easily.
You won't be able to try to match the ID this way, unfortunately. Using .Find(id)
will work as long as the primary key for the entity type specified by T
has a single column and id
is the correct type, but that's going to be a very brittle approach even if it works in some cases.
If you describe your scenario a little bit more, people might have some good suggestions for another approach to take. Can you explain why you want to do this generically? It's pretty unusual to want to execute a query against your DbContext
without knowing what entity type you're interested in.
Upvotes: 4