Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys,

I just want to refresh my knowledge about EF and LinQ thats why I created an app that has the CRUD functionality.Now the problem is that I got the error
"Cannot insert explicit value for identity column in table 'Book' when IDENTITY_INSERT is set to OFF." when executing Add function.I know my code is correct because I always use this code in my previous exercises.

Here is the code in my btnAdd button:
C#
private void CreateBook()
       {
           var book = new Book();
           var addBook = new BookBusinessLayer();
           book.Author = txtAuthor.Text;
           book.Price = decimal.Parse(txtPrice.Text);
           book.Title = txtTitle.Text;
           book.Year = txtYear.Text;
           book.publisherId = int.Parse(dlistPublisher.SelectedValue);//this is Foreign Key
           addBook.AddBook(book);
       }


And when I see the inner exception the value of Book.Id=0
but I didnt set the value of the Book.Id because it is my Primary Key

How should I get rid of this Error

Any comments and Answers will be appreciated :)
Posted

Turn on identity on the table at the database level.
SET IDENTITY_INSERT Book ON
 
Share this answer
 
Comments
The14thNoah 4-Feb-14 22:16pm    
Thanks for your reply
actually that was my choice but all I want is make the Book.Id Autogenerated everytime I add book,so if I turn on the SET_IDENTITY_INSERT
is it still autogenerate the primary key or i will set it manually?

Thanks :)
use this Query

SQL
SET IDENTITY_INSERT Table_Name ON

INSERT INTO Table_Name (ID, name)
VALUES (5, 'David')

SET IDENTITY_INSERT Table_Name OFF
 
Share this answer
 
Comments
The14thNoah 5-Feb-14 0:22am    
tnx for the reply King_Fisher,i just did what you and Abhinav S suggest,I turn on the IDENTITY_INSERT ON in my database.But the error occur again,I guess it because the Book.Id has value which is zero and I dont know where did it get its value
SET Following properties for BOOK’s table Id Column in database

Identity Specification  Yes

(Is Identity)Yes

Identity Increment 1

Identity Seed  1
 
Share this answer
 
Comments
The14thNoah 5-Feb-14 0:28am    
All the said properties were the same in my database.The only thing that confused me was that the Book.Id has Value which is zero even though I dont set its value in code behind thats why the error occur I guess
Thanks for the reply :)
I found the answer. .
what a shame for me,
after I set the identity ON in my database THEN update the .edmx file in my solution and then build it :P
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900