Entity Framework 的 UnitOfWork 模式,但具有直接 SQL 查询

UnitOfWork pattern for Entity Framework but with direct SQL queries

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

我的数据库具有高度规范化的纯关系结构,因为它不是真正的 EF 友好。因此,我创建了映射到实体的视图,以便在查询时我仍然可以拥有所有 EF 和 LINQ 优点,但我必须使用 direct sql queries (例如 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(); 
}

我在 EF 的 UoW:

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 中?

UoW 不会直接与 SQL 一起工作,因为 ADO.net queries/commands 并不懒惰。您需要 ADO.net 个事务来包装所有 SQL 个查询。 UoW 本质上是一种交易模式,它覆盖您的存储库以产生类似交易的行为。