asp.net-mvc-2 - Entity Framework 4 CTP 4/CTP 5 通用存储库模式和可单元测试

标签 asp.net-mvc-2 entity-framework-4 repository-pattern

我正在使用最新的 Entity Framework CTP 5 版本并构建一个简单的 asp.net MVC 博客,其中我只有两个表:发布和评论。这完全是在 POCO 中完成的,我只需要 DbContext 部分的帮助,我需要它进行单元测试(使用 IDbSet?),并且我需要一个简单/通用的存储库模式来添加、更新、删除、检索。任何帮助表示赞赏。

谢谢。

最佳答案

从你的 DbContext 开始,创建一个名为 Database.cs 的新文件:

Database.cs

public class Database : DbContext
    {

        private IDbSet<Post> _posts;

        public IDbSet<Post> Posts {
            get { return _posts ?? (_posts = DbSet<Post>()); }
        }

        public virtual IDbSet<T> DbSet<T>() where T : class {
            return Set<T>();
        }
        public virtual void Commit() {
            base.SaveChanges();
        }
}

定义一个 IDatabaseFactory 并使用 DatabaseFactory 实现它:

IDatabaseFactory.cs
public interface IDatabaseFactory : IDisposable
    {
        Database Get();
    }

DatabaseFactory.cs
public class DatabaseFactory : Disposable, IDatabaseFactory {
        private Database _database;
        public Database Get() {
            return _database ?? (_database = new Database());
        }
        protected override void DisposeCore() {
            if (_database != null)
                _database.Dispose();
        }
    }

一次性延长方法:

Disposable.cs
public class Disposable : IDisposable
    {
        private bool isDisposed;

        ~Disposable()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        private void Dispose(bool disposing)
        {
            if(!isDisposed && disposing)
            {
                DisposeCore();
            }

            isDisposed = true;
        }

        protected virtual void DisposeCore()
        {
        }
    }

现在我们可以定义我们的 IRepository 和我们的 RepositoryBase

IRepository.cs
public interface IRepository<T> where T : class
{
    void Add(T entity);
    void Delete(T entity);
    void Update(T entity);
    T GetById(long Id);
    IEnumerable<T> All();
    IEnumerable<T> AllReadOnly();
}

RepositoryBase.cs
public abstract class RepositoryBase<T> where T : class
    {
        private Database _database;
        private readonly IDbSet<T> _dbset;
        protected RepositoryBase(IDatabaseFactory databaseFactory)
        {
            DatabaseFactory = databaseFactory;
            _dbset = Database.Set<T>();
        }

        protected IDatabaseFactory DatabaseFactory
        {
            get; private set;
        }

        protected Database Database
        {
            get { return _database ?? (_database = DatabaseFactory.Get()); }
        }
        public virtual void Add(T entity)
        {
            _dbset.Add(entity);
        }

        public virtual void Delete(T entity)
        {
            _dbset.Remove(entity);
        }

        public virtual void Update(T entity)
        {
            _database.Entry(entity).State = EntityState.Modified;
        }
        public virtual T GetById(long id)
        {
            return _dbset.Find(id);
        }

        public virtual IEnumerable<T> All()
        {
            return _dbset.ToList();
        }
        public virtual IEnumerable<T> AllReadOnly()
        {
            return _dbset.AsNoTracking().ToList();
        }
    }

现在您可以创建您的 IPostRepository 和 PostRepository:

IPostRepository.cs
     public interface IPostRepository : IRepository<Post>
        {
            //Add custom methods here if needed
            Post ByTitle(string title);
        }

PostRepository.cs
    public class PostRepository : RepositoryBase<Post>, IPostRepository
        {
            public PostRepository(IDatabaseFactory databaseFactory) : base(databaseFactory)
            {
            }
            public Post ByTitle(string title) {
                return base.Database.Posts.Single(x => x.Title == title);
            }
        }

最后,UoW:

IUnitOfWork.cs
public interface IUnitOfWork
{
    void Commit();
}

UnitOfWork.cs
private readonly IDatabaseFactory _databaseFactory;
private Database _database;

public UnitOfWork(IDatabaseFactory databaseFactory)
{
    _databaseFactory = databaseFactory;
}

protected Database Database
{
    get { return _database ?? (_database = _databaseFactory.Get()); }
}

public void Commit()
{
    Database.Commit();
}

在您的 Controller 中使用:
private readonly IPostRepository _postRepository;
private readonly IUnitOfWork_unitOfWork;

        public PostController(IPostRepository postRepository, IUnitOfWork unitOfWork)
        {
            _postRepository = postRepository;
            _unitOfWork = unitOfWork;
        }

        public ActionResult Add(Post post) {
            _postRepository.Add(post);
            _unitOfWork.Commit();
        }

您将需要使用像 StructureMap 这样的 IoC 容器来完成这项工作。您可以通过 NuGet 安装结构图,或者如果您使用的是 MVC 3,则可以安装 StructureMap-MVC NuGet 包。 (以下链接)

Install-Package StructureMap.MVC4

Install-Package StructureMap.MVC3

Install-Package Structuremap

如果您有问题,请告诉我。希望能帮助到你。

关于asp.net-mvc-2 - Entity Framework 4 CTP 4/CTP 5 通用存储库模式和可单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4442828/

相关文章:

asp.net-mvc - 为什么我应该在我的 LINQ To SQL 存储库保存方法中使用 GetOriginalEntityState()?

nhibernate - 我是否应该担心默认情况下ORM返回所有列?

c# - 使用求和和排序依据的 Linq 查询

asp.net-mvc-3 - DDD 在复杂的企业 MVC 应用程序中,存储库的职责是什么,什么属于域?

asp.net-mvc-2 - Silverlight 4.0 + MVC 2.0 + WCF RIA 服务 + EF 4.0 = 加载错误

asp.net-mvc - MVC 2 jQuery 验证和 ajax 表单

c# - 使用 LINQ 将列表复制到不同的列表

entity-framework - Entity Framework 存储库模式为什么不返回 Iqueryable?

design-patterns - 什么属于存储库,什么不属于?

asp.net - 有哪些选项可用于在 ASP.NET MVC2 中存储应用程序设置?