简体   繁体   English

实体框架是否根据数据库值进行更新?

[英]Entity Framework update based on database values?

Before Entity Framework, if I had something like a stock quantity or an on order quantity for a product, I would update it's quantities using the current database values as such: 在Entity Framework之前,如果我有某种产品的库存数量或订单数量,我将使用当前的数据库值来更新其数量,例如:

UPDATE Products SET AvailableQty = AvailableQty - 2 WHERE ProductId = 1;

Is there a way to accomplish the same thing with Entity Framework? 有没有一种方法可以使用实体框架完成相同的工作? It seems like the framework follows a Load, Modify, Update pattern: 似乎该框架遵循加载,修改,更新模式:

Product product = db.Products.FirstOrDefault(x => x.ProductId == 1);
product.AvailableQty += 2;
db.SaveChanges();

However, following this method there is a possibility that the product changes between the initial loading of the data and the update of the data. 但是,采用这种方法后,产品可能会在数据的初始加载和数据更新之间发生变化。 I know I can have a concurrency field on the entity that will prevent the update, but in most cases I don't want to have user intervention (such as a customer placing an order or receiving a purchase order). 我知道我可以在实体上有一个并发字段来阻止更新,但是在大多数情况下,我不想受到用户干预(例如客户下订单或接收采购订单)。

Is there a preferred method to handling situations like these using EF, or should I just fall back to raw SQL for these scenarios? 是否存在使用EF处理此类情况的首选方法,或者对于这些情况,我应该只使用原始SQL吗?

Enclose your find and update within a transaction 将您的发现和更新包含在交易中

using (var transaction = new System.Transactions.TransactionScope())
{
    Product product = db.Products.FirstOrDefault(x => x.ProductId == 1);
    product.AvailableQty += 2;
    db.SaveChanges();
    transaction.Complete();
}

"preferred method" would be opinion-based, so I'll just concentrate on the answer. “首选方法”将基于意见,因此我将集中讨论答案。 EF allows you direct access to the database through the DbContext's Database property. EF允许您通过DbContext的Database属性直接访问数据库。 You can execute SQL directly with ExecuteSqlCommand. 您可以直接使用ExecuteSqlCommand执行SQL。 Or, you can use the SqlQuery extension method. 或者,您可以使用SqlQuery扩展方法。

ExecuteSqlCommand returns the records affected. ExecuteSqlCommand返回受影响的记录。 And, the SqlQuery extension methods lets you use the fill provided by EF. 并且,SqlQuery扩展方法使您可以使用EF提供的填充。

Also, if that is not enough power, you can create your own commands like this: 另外,如果那还不够强大,您可以创建自己的命令,如下所示:

var direct = mydbContext.Database;
using (var command = direct.Connection.CreateCommand())
{
    if (command.Connection.State != ConnectionState.Open) 
    { 
        command.Connection.Open(); 
    }

    command.CommandText = query.ToString(); // Some query built with StringBuilder.
    command.Parameters.Add(new SqlParameter("@id", someId));
    using (var reader = command.ExecuteReader())
    {
        if (reader.Read()) 
        {
            ... code here ...
            reader.Close();
        }
        command.Connection.Close();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM