EntityFramework中的FindBy Id方法 [英] FindBy Id method in EntityFramework

查看:406
本文介绍了EntityFramework中的FindBy Id方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class Repository< T>可以在Entity框架中实现FindBy方法。 :IRepository< T>其中T:class,IAggregateRoot 
{

private readonly DbSet< T> _entitySet;
public IQueryable< T> FindBy(Expression< Func< T,bool>>谓词)
{
// IQueryable< T>查询= _entitySet。
}
}

在这种情况下,我如何实现FindBy!

解决方案

我的存储库具有以下方法通过给定的表达式返回单个实体。

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

现在调用者可以使用任何表达式获取单个实体,如



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

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

如果您的界面IAggregateRoot定义了一个属性Id,您还可以将一个显式方法添加到通用接口通过其ID来获取单个实体。

  public interface IAggregateRoot {
int Id {get;}
}

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


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 !??

解决方案

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

这篇关于EntityFramework中的FindBy Id方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆