简体   繁体   English

EF6在事务中多次调用SaveChanges功能

[英]EF6 Multiple calls SaveChanges function in a transaction

In a transaction, I should call many times SaveChanges() , or just call once ? 在事务中,我应该多次调用SaveChanges(),或者只调用一次?

What is the difference between them? 它们之间有什么区别? Thanks very much. 非常感谢。

Can I only write once SaveChanges() before Commit() function ? 我可以在Commit()函数之前只写一次SaveChanges()吗?

using (var transaction = entities.Database.BeginTransaction())
{
    try
    {
        var product = entities.Product.Add(new Product()
        {
            Name = name,
            Shape = shape
        });

        entities.SaveChanges();  // here

        foreach (var image in images)
        {

            entities.Image.Add(new Image()
            {
                ProductId = product.Id,
                Url = image
            });
        }
        entities.SaveChanges();  // here

        foreach (var specification in specifications)
        {

            entities.Specification.Add(new Specification()
            {
                Name = specification.Split(',')[0],
                Value = specification.Split(',')[1].AsDecimal(),
                ProductId = product.Id
            });
        }
        entities.SaveChanges(); // here

        transaction.Commit();

    }
    catch (Exception)
    {
        transaction.Rollback();
        return Json(new { status = false });
    }
}

Most operations will not need a transaction. 大多数操作不需要交易。 For example, your code can probably be rewritten without a transaction by adding the child entities to navigation properties on the parent, like this: 例如,可以通过将子实体添加到父实体的导航属性中而无需事务来重写代码,如下所示:

var product = entities.Product.Add(new Product()
{
    Name = name,
    Shape = shape
});
foreach (var image in images)
{
    product.Images.Add(new Image()
    {
        Url = image
    });
}
foreach (var specification in specifications)
{
    product.Specifications.Add(new Specification()
    {
        Name = specification.Split(',')[0],
        Value = specification.Split(',')[1].AsDecimal(),
    });
}
entities.SaveChanges();

Your existing code does need a transaction and requires a SaveChanges after the product add, and at the end before committing the transaction. 您现有的代码确实需要进行事务处理,并且在添加产品之后以及在提交事务处理之前最后都需要SaveChanges。 This is because you are referring to the product.Id of the added entity, which only gets generated when you call SaveChanges. 这是因为您引用的是添加实体的product.Id,只有在调用SaveChanges时才会生成该实体。 You can safely remove the second SaveChanges in your code, as you are not referring to generated keys of the images. 您可以安全地删除代码中的第二个SaveChanges,因为您没有引用图像的生成键。

您可以在集合中进行所需的任何更改,然后在进行所有更改后每个上下文仅调用一次SaveChanges。

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

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