【问题标题】:Implementing the Repository and Unit of Work Patterns in ASP.NET在 ASP.NET 中实现存储库和工作单元模式
【发布时间】:2013-12-27 06:24:05
【问题描述】:

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

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 要求。当特定实体类型有特殊要求时,例如更复杂的过滤或排序,您可以创建一个派生类,该类具有该类型的附加方法。 "

谁能详细解释我如何创建派生类并使用这些附加方法?我是否将其他方法作为虚拟方法放入通用存储库中?

请帮忙,我不知道该怎么做。非常感谢。

【问题讨论】:

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


    【解决方案1】:

    这是一个例子:

    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;
            }
        }
    
       // ...
    }
    

    【讨论】:

    • 非常感谢您的回复。我想我的困难在于我将如何使用这个 UserRepository?在那篇文章中,Course course = unitOfWork.CourseRepository.GetByID(id); unitOfWork.CourseRepository.Delete(id);其中 GetByID() 和 Delete() 是 GenericRepository 中的方法。现在 GetByEmail() 在 UserRepository 中。我如何使用它,因为我需要使用这个 UnitOfWork 东西?
    • @martial 检查我的编辑我希望它现在有意义。
    • @martial :) 很高兴我能帮上忙 :) 干杯
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2013-02-05
    相关资源
    最近更新 更多