通用存储库模式和多个选择

pre*_*elb 1 generics asp.net-mvc entity-framework repository-pattern

我正在尝试学习存储库模式并查看通用存储库,我无法看到如何处理自定义的select语句.例如,使用本文,作者使用select by ID和select all.

public interface IGenericRepository<T> where T:class
{    
    IEnumerable<T> SelectAll();
    T SelectByID(object id);
    void Insert(T obj);    
    void Update(T obj);    
    void Delete(object id);    
    void Save();
}
Run Code Online (Sandbox Code Playgroud)

后来文章使用Northwind实现了IGenericRepository接口.然后,它用于创建Customer控制器.

public class CustomerController : Controller
{    
    private IGenericRepository<Customer> repository = null; 
    public CustomerController()    
    {        
        this.repository = new GenericRepository<Customer>();    
    }
    ...
Run Code Online (Sandbox Code Playgroud)

这将处理按ID选择所有客户或一个客户的列表,但是我遇到的是一些更真实的例子,例如"为客户选择所有客户"或"选择区域的所有客户".另外,您可以使用另一个基于不同实体的控制器来过滤不同的属性.我想我错过了一些基本的东西.如果用户界面需要通过各种过滤器呈现Customer实体(或任何其他实体),那么如何通过坚持使用一个通用存储库来实现?

Aja*_*kar 6

干得好; 从ID处理任何选择的标准之余,您可以添加其中的方法如下面

public interface IGenericRepository<T> where T:class
{    
    IEnumerable<T> SelectAll();
    T SelectByID(object id);
    IEnumerable<T> Where(Expression<Func<T,bool>> predicate)// this one 
    void Insert(T obj);    
    void Update(T obj);    
    void Delete(object id);    
    void Save();
}
Run Code Online (Sandbox Code Playgroud)

现在在Where方法实现中这样做

public IEnumerable<T> Where(Expression<Func<T,bool>> predicate)
    {
        return _objectSet.Where(predicate).AsEnumerable();
    }
Run Code Online (Sandbox Code Playgroud)

这里_objectSet在存储库构造函数中创建如下:

public Repository(ObjectContext context)
        {
            _context = context;
            _objectSet = _context.CreateObjectSet<T>();
         }

public CustomerController()
    {
        _context = new NorthwindEntities();
        _reporsitory = new Repository<Customer>(_context);

    } 
Run Code Online (Sandbox Code Playgroud)

使用Where方法之类的

 reporsitory.Where(c=>c.Country=="Canada").ToList();
Run Code Online (Sandbox Code Playgroud)

有关完整参考,请参阅codeplex上的此项目(下载/浏览源代码) https://efgenericrepository.codeplex.com/SourceControl/latest