【问题标题】:UnitOfWork pattern for Entity Framework but with direct SQL queries实体框架的 UnitOfWork 模式,但具有直接 SQL 查询
【发布时间】:2016-12-26 00:56:48
【问题描述】:

我正在尝试为我的 ASP.NET MVC 项目合并工作单元模式,它与其他典型的 UoW 设计与实体框架有点不同。

我的数据库具有高度规范化和纯关系结构,因为它不是真正EF 友好。因此,我创建了映射到实体的视图,以便在查询时仍然可以拥有所有 EF 和 LINQ 优点,但在更新时我必须使用 直接 sql 查询(例如 Context.Database.ExecuteSqlCommand)实体。

这对我的 UoW 设计提出了挑战。据我所知,使用 EF 处理 UoW 的一般方法基本上是仅在调用 UoW.Commit() 时才调用 Context.SaveChanges()。这样,所有跟踪的实体更改都将作为单个事务一次提交到数据库。

但是,由于我使用的是Context.Database.ExecuteSqlCommand,所以每当我更新实体时,事务都会立即发生,因此失去了 UoW 的全部意义。我举个例子:

带有 EF 的传统 UoW:

public void CreateOrder()
{
    var customer = new Customer();
    // this only adds the entity to the Context for tracking
    // e.g. Context.Customers.Add(customer);
    UoW.CustomerRepo.Add(customer); 

    // this too only adds the entity to the Context
    var order = new Order();
    UoW.OrderRepo.Add(order);

    // Commit. this internally calls Context.SaveChanges()
    // sending all changes to the db in a single transaction
    // Perhaps also with a TransactionScope.
    UoW.Commit(); 
}

我的 UoW 与 EF:

public void CreateOrder()
{
    var customer = new Customer();
    // this inserts a customer to the db immediately
    // e.g. Context.Database.ExecuteSqlCommand(insertSql);
    UoW.CustomerRepo.Add(customer); 

    // This too inserts an order immediately
    var order = new Order();
    UoW.OrderRepo.Add(order);

    // There is no point calling Context.SaveChanges()
    // here as all my changes are already executed with direct sql.
    UoW.Commit(); 
}

有人遇到过类似的问题吗?我应该在这里放弃 UoW 并简单地将我所有的存储库操作包装在一个 TransactionScope 中吗?

【问题讨论】:

  • 看看这个 SO(61 票的答案):stackoverflow.com/questions/815586/…
  • 只要在发出命令之前开始事务,就可以将 EF 和 ExecuteSqlCommand 结合起来。而且,如果我没记错的话,当要求 EF 保存更改时,它将使用现有事务(如果可用)。
  • 感谢这位朋友,这篇文章很有帮助。我最终放弃了 UoW,只使用了事务范围。

标签: c# asp.net-mvc entity-framework design-patterns unit-of-work


【解决方案1】:

UoW 不适用于直接 SQL,因为 ADO.net 查询/命令不是惰性的。您需要 ADO.net 事务来包装所有 SQL 查询。 UoW 本质上是一种事务模式,它包裹您的存储库以产生类似事务的行为。

【讨论】:

  • 感谢您的直截了当的回答,我知道即使在圣诞节期间我仍然可以得到 SO 的帮助 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-03
  • 1970-01-01
  • 2017-07-28
相关资源
最近更新 更多