[英]Entity Framework doesn't update bit datatype
我添加了一個新列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
典型的懷疑是在運行時應用程序使用的數據庫實例與您正在檢查的數據庫實例不同。 使用斷點驗證使用的連接字符串 /w var conn = DbEntity.Database.Connection.ConnectionString
( var conn = DbEntity.Database.Connection.ConnectionString
) 或DbEntity.Database.GetDbConnection().ConnectionString
for pre-EFCore 5,或DbEntity.Database.ConnectionString
for EF Core 5。 (謝謝微軟...)
在您的示例中,完全沒有必要使用 TransactionScope,並且在 TransactionScope 實用的情況下,您會錯誤地使用它們。 TransactionScope 應該是最外層的邊界, using (var DbEntity = ...
在范圍內聲明。
TransactionScopes 為處理增加了額外的成本,並將用於協調 DbContext 操作和其他外部操作之間的事務,例如與其他 DbContexts 或其他符合事務提交/回滾策略的服務等的操作。 DbContexts 本質上在內部與事務一起操作,因此無論您在 DbContext 范圍內更新多少實體以及它的SaveChanges
調用,它們都將保存在單個事務中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.