0

我添加了一个新列IsForceLogOff(数据类型 = 位)。当我以通常的方式更新表格时,除了新添加的 bool 列之外,所有内容都会更新。

public static UserErrorStatus UserUpdate(User user, Company company)
{
    UserErrorStatus status = UserErrorStatus.Error;

    using (OAPDataLayerEntities DbEntity = GetDBContext())
    {
        try
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                user.IsForceLogOff = true;
                DbEntity.Users.Attach(user);
                DbEntity.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);

                DbEntity.SaveChanges();
                transaction.Complete();

                DbEntity.AcceptAllChanges();
                status = UserErrorStatus.Success;
            }
        }
    }
}

在此处输入图像描述

创建表语句:

CREATE TABLE [dbo].[User]
(
    [UserID] [int] IDENTITY(1,1) NOT NULL,
    [AddressID] [int] NULL,
    [AccountTypeID] [int] NOT NULL,
    [StaffID] [int] NULL,
    [SalutationID] [int] NULL,
    [FirstName] [nvarchar](50) NOT NULL,
    [LastName] [nvarchar](50) NOT NULL,
    [EmailAddress] [nvarchar](100) NOT NULL,
    [Password] [nvarchar](50) NOT NULL,
    [SecurityQuestionID] [int] NOT NULL,
    [SecurityAnswer] [nvarchar](50) NOT NULL,
    [PhoneNumber1] [nvarchar](50) NULL,
    [PhoneNumber2] [nvarchar](50) NULL,
    [Fax] [nvarchar](50) NULL,
    [CompanyID] [int] NULL,
    [DateCreated] [smalldatetime] NOT NULL,
    [DateModified] [smalldatetime] NOT NULL,
    [DateLastLogin] [smalldatetime] NOT NULL,
    [UserIDModified] [int] NULL,
    [StatusID] [int] NOT NULL,
    [Notes] [ntext] NULL,
    [IsForceLogOff] [bit] NOT NULL
)

参考上面的sql

4

1 回答 1

1

典型的怀疑是在运行时应用程序使用的数据库实例与您正在检查的数据库实例不同。使用断点验证使用的连接字符串 /w var conn = DbEntity.Database.Connection.ConnectionString(EF6) 或DbEntity.Database.GetDbConnection().ConnectionStringEFCore 5 之前的版本或DbEntity.Database.ConnectionStringEF Core 5。(感谢 Microsoft...)

在您的示例中,完全没有必要使用 TransactionScope,并且在 TransactionScope 可行的情况下,您使用它们的方式是错误的。TransactionScope 应该是最外面的边界,using (var DbEntity = ...在范围内声明。

TransactionScopes 为处理增加了额外的成本,并将用于协调 DbContext 操作和其他外部操作之间的事务,例如与其他 DbContexts 或其他符合事务提交/回滚策略的服务等的操作。DbContext 本质上在内部与 Transaction 一起操作,因此无论您在 DbContext 范围内更新多少实体并对其SaveChanges进行调用,它们都将保存在单个事务中。

于 2021-11-13T07:23:24.290 回答