[英]Cannot Insert custom value into identity column - Entity Framework
我試圖關閉身份以插入我自己的值,我遵循的步驟
StoredGeneratedPattern
值更改為None
StoredGeneratedPattern
值更改為None
嘗試使用以下代碼
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
int k = Context.ExecuteStoreCommand("SET IDENTITY_INSERT dbo.client ON");
Context.ClientInfoes.Add(testclient);
result = Context.SaveChanges();
int j = Context.ExecuteStoreCommand("SET IDENTITY_INSERT dbo.client OFF");
scope.Complete();
}
但我仍然收到錯誤
當IDENTITY_INSERT設置為OFF時,無法在表中插入標識列的顯式值
我錯過了什么嗎? 還有其他選擇嗎?
調用TransactionScope.Complete時,數據存儲在數據庫中,而不是在調用ClientInfoes.Add或Context.SaveChanges時。 因此,您可以看到,當調用insert語句時,您已經關閉了IDENTITY INSERT。
簡單地重新安排事情......
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
int k = Context.ExecuteStoreCommand("SET IDENTITY_INSERT dbo.client ON");
Context.ClientInfoes.Add(testclient);
result = Context.SaveChanges();
scope.Complete();
int j = Context.ExecuteStoreCommand("SET IDENTITY_INSERT dbo.client OFF");
}
更好的是,在事務之外對IDENTITY_INSERT進行所有更改,因為它的值是特定於會話的(每個會話只能為一個表啟用它)。
在這里看到類似的問題。
Eranga解釋說:
ExecuteSqlCommand
將打開連接,執行sql然后關閉它。 所以你的下一個命令將使用不同的連接執行。
ExecuteSqlCommand方法類似於ExecuteStoreCommand。
Daniel Liuzzi解釋說:
......訣竅是將所有東西都包裝成一個命令......
所以,例如,
string sqlStatement = "SET IDENTITY_INSERT clientInfo ON;" +
string.Format("INSERT clientInfo (ClientInfoId, Column1, Column2) VALUES ({0}, {1}, {2}, '{3}');", testClient.ClientInfoId, testClient.Column1, testclient.Column2) +
"SET IDENTITY_INSERT clientInfo OFF";
context.ExecuteStoreCommand(sqlStatement);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.