简体   繁体   English

EF Core 事务 - 我做对了吗?

[英]EF Core transactions - am I doing it right?

What I know is EF creates transaction for DbContext.SaveChanges .我所知道的是 EF 为DbContext.SaveChanges创建事务。 But I need a block of operations including inserts and I need identity results from them to complete my sequence.但是我需要一个包括插入在内的操作块,并且我需要它们的身份结果来完成我的序列。 So what I do looks like this:所以我所做的看起来像这样:

using var dbTransaction = context.DataBase.BeginTransaction();
try {
    context.Add(myNewEntity);
    context.SaveChanges();
    otherEntity.RefId = myNewEntity.Id;
    context.Update(otherEntity);
    // some other inserts and updates
    context.SaveChanges();
    dbTransaction.Commit();
}
catch {
    dbTransaction.Rollback();
    throw;
}

So I call SaveChanges on inserts to get identities and not to break relations.所以我在插入时调用SaveChanges来获取身份而不是破坏关系。 It looks like transactions in transactions.它看起来像交易中的交易。 Is it correct?这是对的吗? Is it how it should be done?是不是应该怎么做? I mean - Commit doesn't require SaveChanges ?我的意思是- Commit不需要SaveChanges吗? I assume it just saves the changes, but I want to be sure.我认为它只是保存更改,但我想确定。

Your code will be working properly, but I prefer to do it this way:您的代码将正常工作,但我更喜欢这样做:

try {
    context.Add(myNewEntity);
   var result= context.SaveChanges();
    if(result==0){
       dbTransaction.Rollback();
        ... return  error
     }
    otherEntity.RefId = myNewEntity.Id;
    context.Update(otherEntity);
    // some other inserts and updates
    result=context.SaveChanges();
if(result==0){
       dbTransaction.Rollback();
        ... return  error
     }
    dbTransaction.Commit();
}
catch {
    dbTransaction.Rollback();
    throw;
}

It is very usefull if for example you update or add or delete several records.例如,如果您更新或添加或删除多条记录,这将非常有用。 In this case the result will return the number of effected records and instead of result==0 I usually use if result <...effected records I expect.在这种情况下,结果将返回影响记录的数量,而不是 result==0 我通常使用 if result <...我期望的影响记录。

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

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