[英]Entity Framework: Cannot insert explicit value for identity column in table '[table]' when IDENTITY_INSERT is set to OFF
[英]Cannot insert explicit value for identity column in table 'candidatedetails' when IDENTITY_INSERT is set to OFF
我正在解決這個錯誤。 我該怎么解決這個問題?
這是我的創建查詢
CREATE TABLE [dbo].[candidatedetails](
[id] [int] IDENTITY(1,1) NOT NULL,
[cname] [varchar](50) NULL,
[pname] [varchar](50) NULL,
[cno] [varchar](50) NULL,
[pno] [varchar](50) NULL,
[address] [varchar](max) NULL,
[year] [varchar](50) NULL,
[class] [varchar](50) NULL,
[branch] [varchar](50) NULL,
[totalfees] [numeric](18, 0) NULL,
[paidfees] [numeric](18, 0) NULL,
[pendingfees] [numeric](18, 0) NULL,
[idno] [int] NULL,
CONSTRAINT [PK_candidatedetails] PRIMARY KEY CLUSTERED
(
[id] ASC
)
這是代碼
SqlConnection con = new SqlConnection(constring);
con.Open();
if(con.State==ConnectionState.Open)
{
string q = "INSERT INTO candidatedetails(id,cname,pname,cno,pno,address,year,class,branch,totalfees,paidfees,pendingfees,idno) VALUES ('','"+cname+"','"+pname+"','"+cno+"','"+pno+"','"+address+"','"+year+"','"+class1+"','"+branch+"','"+totalfees+"','"+paidfees+"','"+pendingfees+"','"+idno+"')";
SqlCommand com = new SqlCommand(q, con);
com.ExecuteNonQuery();
MessageBox.Show("Candidate is registered");
}
我在“com.executenonquery()”行上收到此錯誤
您的id
列被聲明為IDENTITY
因此它會在插入時自動生成一個值。 您不必將其包含在插入列列表中,也不必為其提供值。
string q = "INSERT INTO candidatedetails(cname,pname,cno,pno,address,year,class,branch,totalfees,paidfees,pendingfees,idno) VALUES ('"+cname+"','"+pname+"','"+cno+"','"+pno+"','"+address+"','"+year+"','"+class1+"','"+branch+"','"+totalfees+"','"+paidfees+"','"+pendingfees+"','"+idno+"')";
另外,要注意像這樣動態生成SQL,它容易出錯 (例如,如果你的一個值有一個未轉義的單引號),如果值來自用戶輸入或另一個不安全的源,則會出現SQL注入 。
您應該創建一個接收這些參數的存儲過程,或者使用sp_executesql
構建sql。
只需刪除id表單sql查詢:試試這個:
SqlConnection con = new SqlConnection(constring);
con.Open();
if(con.State==ConnectionState.Open)
{
string q = "INSERT INTO candidatedetails(cname,pname,cno,pno,address,year,class,branch,totalfees,paidfees,pendingfees,idno) VALUES ('"+cname+"','"+pname+"','"+cno+"','"+pno+"','"+address+"','"+year+"','"+class1+"','"+branch+"','"+totalfees+"','"+paidfees+"','"+pendingfees+"','"+idno+"')";
SqlCommand com = new SqlCommand(q, con);
com.ExecuteNonQuery();
MessageBox.Show("Candidate is registered");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.