I have a common repository base class for LINQ-to-Entities that can do things such as selecting an object based on an identifier.
To subclass it, you need to implement the following two:
protected override Expression<Func<User, bool>> GetByIDSelector(int id)
{
return u => u.UserID == id;
}
protected override Expression<Func<User, int>> KeySelector
{
get { return u => u.UserID; }
}
I would just like to use KeySelector(which is used for the default sort order).
My get by ID method looks like this:
public virtual TDataModel GetByID(TKey id)
{
var entity = SetProvider.Set<TDataModel>().Where(GetByIdSelector(id)).SingleOrDefault();
if (entity == null)
{
throw new EntityNotFoundException<TDataModel>(id);
}
return entity;
}
Where GetByIdSelectorit looks like that should turn the expression KeySelectorinto one that can be selected by identifier.
private Expression<Func<TDataModel, bool>> GetByIdSelector(TKey id)
{
return Expression.Lambda<Func<TDataModel, bool>>
(
Expression.Equal(KeySelector.Body,
Expression.Constant(id)),
KeySelector.Parameters.Single()
);
}
However, the Entity Framework throws an exception that is passed to this parameter unrelated to the request.
The 'u' parameter was not bound in the specified LINQ to Entities query expression.
- KeySelector ?