FindBy Id method in EntityFramework

2019-08-06 18:16发布

问题:

it is possible to implement FindBy method in Entity framework while we have this GenericRepository class :

public class Repository<T> : IRepository<T> where T : class, IAggregateRoot
    {

        private readonly DbSet<T> _entitySet;
public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
        {
            //IQueryable<T> query=_entitySet.
        }
}

how can I Implement FindBy in this case !??

回答1:

My Repository has the following method to return a single entity by a given expression.

public T FindSingle(Expression<Func<T, bool>> predicate) {
  return _entitySet.FirstOrDefault(predicate);
}

Now the caller can use any expression to get a single entity, like

var entity = _repository.FindSingle(entity=> entity.Id == 23);

or

var entity = _repository.FindSingle(entity=> entity.Name == "Hello World");

If your interface IAggregateRoot defines a property Id you can also add an an explicit method to your generic interface to get a single entity by its Id.

public interface IAggregateRoot {
  int Id {get;}
}

public class GenericRepository {
  public T FindSingleById(int id) {
    return _entitySet.FirstOrDefault(entity=>entity.Id == id);
  }
}


回答2:

This should work

public class Repository<T> : IRepository<T> where T : class, IAggregateRoot
    {

        private readonly DbSet<T> _entitySet;
        public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
        {
            return _entitySet.Where(predicate).
        }
}