[英]SqlException: Cannot insert explicit value for identity column in table [Table name] when IDENTITY_INSERT is set to OFF
[英]Cannot insert explicit value for identity column in table 'ClientDetails' when IDENTITY_INSERT is set to OFF
每當我嘗試通過表單將數據提交到此數據庫時,我都會拋出此異常: -
例外
當IDENTITY_INSERT設置為OFF時,無法在表'ClientDetails'中為identity列插入顯式值。
但是,表單沒有字段,因此數據可以進入標識列(PK),因此我不知道為什么會出現這種情況。
目前我正在使用標准的asp.net mvc提交按鈕,但我最終將它鏈接到一個jquery對話框按鈕
ClientNo列是異常所指的列,具有以下屬性
ClientNo有900以后的數據等
當客戶端表單沒有在表單中輸入數據時,也會拋出此異常
它拋出在DataCOntext.SubmitChanges()方法上
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create1(ClientDetail client)
{
if(ModelState.IsValid)
{
client = new ClientDetail();
UpdateModel(client);
//Debug Code
System.Diagnostics.Debug.WriteLine("AddNewClient Create1");
repo.AddNewClient(client);
//Debug Code
System.Diagnostics.Debug.WriteLine("Save Create1");
// System.Data.SqlClient.SqlException thrown at this line
repo.Save();
//Debug Code - never reached
System.Diagnostics.Debug.WriteLine("Saved Changes");
// return RedirectToAction("Details", new { id = client.ClientNo });
}
return View(client);
}
public void AddNewClient(ClientDetail client)
{
System.Diagnostics.Debug.WriteLine("Start Insert On Submit");
db.ClientDetails.InsertOnSubmit(client);
System.Diagnostics.Debug.WriteLine("Finish Insert On Submit");
}
public void Save()
{
System.Diagnostics.Debug.WriteLine("In Save Method");
db.GetChangeSet();
System.Diagnostics.Debug.WriteLine("Got ChangeSet");
db.SubmitChanges();
System.Diagnostics.Debug.WriteLine("Exit Save Method");
}
Is this the query everyone is talking about
[Column(Storage="_ClientNo", DbType="Int NOT NULL", IsPrimaryKey=true, UpdateCheck=UpdateCheck.Never)]
public int ClientNo
{
get
{
return this._ClientNo;
}
set
{
if ((this._ClientNo != value))
{
this.OnClientNoChanging(value);
this.SendPropertyChanging();
this._ClientNo = value;
this.SendPropertyChanged("ClientNo");
this.OnClientNoChanged();
}
}
}
有沒有人知道為什么會發生這種情況的解決方案或原因?
謝謝
將IsDbGenerated = true添加到ClientNo屬性
[Column(Storage="_ClientNo", DbType="Int NOT NULL", **IsDbGenerated=true,** IsPrimaryKey=true, UpdateCheck=UpdateCheck.Never)]
public int ClientNo
您不能提供要作為插入的一部分插入Identity列的值。 它們自動生成為INSERT
操作的原子部分。 使用SET IDENTITY_INSERT
命令可以基於每個表暫時禁用此功能。
或者,您應該更改數據庫shcema,但我不建議使用此更好或更好,您不應提供值,或為插入中的Client_NO
列提供NULL
值。
在SQL中,您可以使用SCOPE_IDENTITY()
函數來獲取自動生成的值。 模型將使用此值自動更新。
使用archil的答案告訴模型不要在生成的選擇中傳遞此列。
[Column(Storage="_ClientNo",
DbType="Int NOT NULL",
IsDbGenerated=true,
IsPrimaryKey=true,
UpdateCheck=UpdateCheck.Never)]
public int ClientNo
請注意IsDBGenerated版本的arrtributes。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.