So I’m trying to create a generic select by ID method for a base repository class. In order to achieve this I’m using EF4 with POCO’s. I created an interface with a getter called Id and successfully modified the T4 template in order to have a generic Id property in all the entities that returns the PK.
The problem comes when I use the query. I’m implementing it like this:
public virtual T GetByID(int id)
{
return Database.ObjectSet<T>().SingleOrDefault(entity => entity.Id == id);
}
And even though all the entities returned by the ObjectSet have the Id property set with their current primary key value, I’m getting a weird error:
The specified type member ‘Id’ is not
supported in LINQ to Entities. Only
initializers, entity members, and
entity navigation properties are
supported.
Am I missing something?
If the generic Id only (as you mention) “returns the PK” but is not actually mapped to the PK itself, then there is no way for EF to convert this to a SQL query.
One pattern I’ve used in the past: if all of your entities will have an int PK called Id then you can have all of them inherit from some baseclass where that Id property is defined (and mapped to) and then add a where clause to your generic method:
FYI, I’ve also used this with entities with different types of PKs using generics.