Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

c# - SQL Identity column if no input value in insert query in ADO.NET throws exception that it can't be null

I have an identity column in the DB which is primary key and increments its value by itself. But I have a insert query in asp.net ado.net class like below:

cmd = new SqlCommand("insert into Images(Name,[Image]) VALUES ('Nature',@img)", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("@img", SqlDbType.Image).Value = img;
cmd.ExecuteNonQuery();

However, it throws me exception that it cannot be null.

My idea/goal is, I just want to insert the above two values only and the primary key column should increment by itself internally in DB. I have configured that in DB. However I don't know how to handle this error or tweak this code. Please help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Make sure the ID column on your Images table is an identity column.

For example:

CREATE TABLE Images(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](100) NOT NULL,
    [Image] [image] NOT NULL)

If it is, then step through your code and make sure the parameters you are using are not null; TextBox1.Text and img.

Lastly, make sure there are no other non-nullable columns on the table.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...