Expressions: get-by-ID-selector, when do I have an expression to get an identifier?

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 ?

+3
1

, , this.KeySelector, - (, KeySelector.Parameters.Single() , KeySelector.Body). , .

private Expression<Func<TDataModel, bool>> GetByIdSelector(TKey id)
{
    var keySelector = KeySelector;
    return Expression.Lambda<Func<TDataModel, bool>>(
        Expression.Equal(
            keySelector.Body,
            Expression.Constant(id)
        ), 
        keySelector.Parameters.Single()
    );
}

, , , , KeySelector , .

:

private static readonly Expression<Func<User, int>> _keySelector = u => u.UserID;

protected override Expression<Func<User, int>> KeySelector
{
    get { return _keySelector; }
}

, - GetByIdSelector .

+3

Source: https://habr.com/ru/post/1793625/


All Articles