在ASP.NET中实现存储库和工作单元模式

时间:2013-12-27 06:24:06

标签: c# asp.net entity-framework repository unit-of-work

有没有人在www.asp.net上读过这篇文章 “在ASP.NET MVC应用程序中实现存储库和工作单元模式(第9步,共10步)”

http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

在文章中它说:“这个通用存储库将处理典型的CRUD要求。当特定实体类型有特殊要求时,例如更复杂的过滤或排序,您可以创建一个派生类,该类具有该类型的其他方法。 “

任何人都可以详细解释如何创建派生类并使用这些额外的方法?我是否将其他方法作为虚拟方法添加到通用存储库中?

请帮助,我无法弄清楚如何做到这一点。非常感谢。

1 个答案:

答案 0 :(得分:3)

以下是一个例子:

public class GenericRepository<TEntity> where TEntity : class
{
    public virtual TEntity GetByID(object id)
    {
        // ...
    }

    public virtual void Insert(TEntity entity)
    {
        // ...
    }

    public virtual void Delete(TEntity entityToDelete)
    {
        // ...
    }
}

这些方法适用于您的所有实体。但是,假设您希望通过电子邮件获取User(只有用户拥有的属性),您可以使用其他方法扩展GenericRepository

public class UserRepository : GenericRepository<User>
{
    // Now the User repository has all the methods of the Generic Repository
    // with addition to something a bit more specific
    public User GetByEmail(string email)
    {
        // ..
    }
}

编辑 - 在文章中,他们在工作单元中使用GenericRepository,但是当您的存储库更具体时,您可以使用它。例如:

public class UnitOfWork : IDisposable
{
    private GenericRepository<Department> departmentRepository;
    private GenericRepository<Course> courseRepository;

    // here is the one we created, which is essentially a GenericRepository as well
    private UserRepository userRepository;

    public UserRepository UserRepository
    {
        get
        {

            if (this.userRepository== null)
            {
                this.userRepository= new UserRepository(context);
            }
            return this.userRepository;
        }
    }

   // ...
}
相关问题