FindBy Id method in EntityFramework

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-13 01:41:43

问题


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).
        }
}


来源:https://stackoverflow.com/questions/14865013/findby-id-method-in-entityframework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!