C# 当我不需要做更多的事情时,我需要做回滚或其他什么?

C# 当我不需要做更多的事情时,我需要做回滚或其他什么?,c#,.net,entity-framework-6,transactionscope,C#,.net,Entity Framework 6,Transactionscope,我有一个返回bool的方法: using(Entities dbContext = new Entities()) { using (DbContextTransaction myTransaction = dbContext.Database.BeginTransaction()) { //Get data from database //check data from database //if my data is the

我有一个返回bool的方法:

using(Entities dbContext = new Entities())
{
    using (DbContextTransaction myTransaction = dbContext.Database.BeginTransaction())
    {
        //Get data from database

        //check data from database

        //if my data is the expected: return true;
            //???: rollback or something to do or is it enough with the return?


        //if not is expected:
            //update data;
            //dbContext.Savechages();
            //myTransaction.Commit();
            //return true;
    }
}
我的疑问是,如果我不必对数据做更多的处理,那么返回true就足够了,还是建议执行回滚或提交而不保存更改


谢谢。

您应该在开始交易前检查数据,当您从数据库读取数据时,您不需要开始交易,因为逻辑的第一部分没有任何更新,请插入。。。您不需要任何提交或回滚

实际上你的代码应该是这样的

using(Entities dbContext = new Entities())
{
        //Get data from database

        //check data from database

        //if my data is the expected: return true;

using (DbContextTransaction myTransaction = dbContext.Database.BeginTransaction())
    {
         //if not is expected:
            try 
             {
               //update data;
               //dbContext.Savechages();
               //myTransaction.Commit();
               //return true;
             }
           catch(Exception ex)
           {
            transaction.Rollback();
            ......
            return false;
        }
    }
}

如果您正在读取数据,但对其不做任何操作,则无需回滚,因为没有任何内容可回滚。谢谢。但是,如果我在检查数据后打开事务,其他用户可以修改数据,当我打开事务时,我无法确定数据是否具有预期值。如果我使用事务,则是为了确保.begin transaction无法锁定您的表或表行,如果您处于begin transaction块中,此时其他用户可以更改数据库中的数据,则没有任何锁定,尝试锁定行,或检查您的行状态是否已更改或没有。。。您可以像这样使用RowVersion是的,在我的simplify示例中,我不想解释在我的示例中我想使用伪同位并发。但是对于EF,如果我不使用UPDLOCK之类的点击来阻止行,那么在我看来,没有理由使用事务,因为dbContext是一个事务。