您是否将存储库模式与Entity Framework一起使用?

时间:2014-11-25 08:25:29

标签: c# .net asp.net-mvc entity-framework repository

有些人说我们不应该使用存储库和工作单元模式,因为存储库& UnitOfWork只是重复实体框架(EF)DbContext给你的东西。 但是如果我使用存储库,我可以编写简单的服务单元测试,因为我可以从存储库模拟方法(使用linq查询从数据库返回数据),例如:

存储库:

public class CommentsRepository : ICommentsRepository
{
    public CommentsRepository(DatabaseContext context)
        : base(context)
    {
    }

    public IEnumerable<Comment> GetComments()
    {
        return context.Comments.Include(x => x.Note).OrderByDescending(x => x.CreatedDate).ToList();
    }
}

服务:

public class CommentsService : ICommentsService
{
    private ICommentsRepository _commentsRepository;

    public CommentsService(ICommentsRepository commentsRepository)
    {
        _commentsRepository = commentsRepository;
    }

    public IEnumerable<Comment> GetComments()
    {
        List<Comment> comments = _commentsRepository.GetComments().ToList();

        comments.ForEach(x => x.Author = "Secret");

        return comments;
    }
}

服务单元测试:

[TestClass]
public class CommentsServiceTest
{
    [TestMethod]
    public void GetCommentsTest()
    {
        // Arrange
        IList<Comment> comments = Builder<Comment>.CreateListOfSize(2)
            .Build();

        AutoMoqer mocker = new AutoMoqer();
        mocker.GetMock<ICommentsRepository>()
                .Setup(x => x.GetComments())
                .Returns(comments);

        // Act
        ICommentsService commentsService = mocker.Resolve<CommentsService>();
        IList<Comment> result = commentsService.GetComments().ToList();

        // Assert
        Assert.AreEqual("Secret", result[0].Author);
        Assert.AreEqual("Secret", result[1].Author);
    }
}

现在,当我消除存储库时,我必须在服务中编写linq查询:

public class CommentsService : ICommentsService
{
    private DatabaseContext _context;

    public CommentsService(DatabaseContext context)
    {
        _context = context;
    }

    public IEnumerable<Comment> GetComments()
    {
        List<Comment> comments = _context.Comments.Include(x => x.Note).OrderByDescending(x => x.CreatedDate).ToList();

        comments.ForEach(x => x.Author = "Secret");

        return comments;
    }
}

为该服务编写单元测试是有问题的,因为我必须模拟:

context.Comments.Include(x => x.Note).OrderByDescending(x => x.CreatedDate)

那你做什么?你是否编写了存储库类?如果没有,你如何模拟linq查询?

1 个答案:

答案 0 :(得分:4)

与所有模式一样,如果它适合您的目的,那么您应该使用它。

我编写了一个包含Entity Framework的工作单元和存储库模式实现。不仅如此,我还可以进行测试,而是将EF从我的应用程序中抽象出来。

后来切换到内存数据库中进行“实时”测试,这是一件轻而易举的事。

相关问题