c# - 为什么要在存储库中包含 Repo.SaveChanges() 方法?

标签 c# entity-framework repository-pattern

我正在与另一位开发人员讨论是否要在我们的 Entity Framework 5 存储库中公开一个 repo.SaveChanges() 方法。

我们正在考虑有一个像这样自动保存更改的 repo(快速和肮脏的例子):

public class Repo {
    private OurEfContext _context = new OurEfContext();

    public void PersistCustomer(Customer cust)
    {
        // update customer code here
        _context.SaveChanges(); //  <-- is this okay?
    }
}

我们正在考虑的另一个选择是公开一个单独的 Repo.PersistChanges() 方法,如下所示:

public class Repo {
    private OurEfContext _context = new OurEfContext();

    public void PersistCustomer(Customer cust)
    {
        // update customer code here
        // no call to _context.SaveChanges();
    }

    public void PersistChanges()
    {
        _context.SaveChanges();
    }
}

我见过的大多数示例都使用第二种模式。一种模式比另一种模式更“正确”吗?

最佳答案

在每次更改后保存会阻止您保存成批的实体。在某些图形结构中,这可能是一个正确性问题,在其他情况下,它只会增加 CPU 负载。 SaveChanges 的成本不仅仅是写入,还包括遍历加载到上下文中的实体。

为什么反对 Entity Framework ?执行它要您执行的操作:保存批处理并在对实体进行所有更改后最后调用 SaveChanges

PersistCustomer 方法的命名有误:它保留所有内容,而不仅仅是客户。您不能使用 EF 保留单个实体。您的抽象(存储库)已损坏。

人们经常将 EF 包装在一个不添加任何功能但删除功能的通用存储库中。这对我来说从来没有意义。

关于c# - 为什么要在存储库中包含 Repo.SaveChanges() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14389858/

相关文章:

c# - Expression<Func<..>>.Compile() 的实际类型是什么?

c# - Entity Framework 中的 self 加入

c# - EF Core Oracle 时间戳与时区到 C# 中的 DateTime

c# - 尝试在 Visual Studio v15.8.4 中的 Entity Framework v6.2.0 中迁移数据库时出现异常

.net - 存储库模式以及域模型和 Entity Framework 之间的映射

asp.net - 存储库模式最佳实践

c# - 没有 ORM 的数据访问层

c# - 如何以编程方式从当前项目构建和编译另一个 c# 项目

c# SerialPort PinChanged 事件处理

c# - 使用 String.Format 为数字添加逗号和