views:

57

answers:

2

i am trying to insert a row to a table with an identity column and three "normal" columns using entity framework in wpf. however i got this error message: Cannot insert explicit value for identity column in table 'MyTable' when IDENTITY_INSERT is set to OFF here is my code snippet, trying to add to the user table who has name, surname, age and userID(identity) column:

        var newuser = new User();
        newuser.SurName = surNameTextBox.Text;
        newuser.Name = nameTextBox.Text;
        newuser.Age = Int32.Parse(ageTextBox.Text);
        context.AddToUsers(newuser);
        context.SaveChanges();

can anyone help me on solving this problem? thanks in advance.

+1  A: 

Identity columns indeed update themselves - that is their purpose.

If this is the only code that you are using to update the User, then I would look at (or post) the AddToUsers method in the DataContext.

Wonko the Sane
i couldn't find anywhere that i assigned the userID but while debugging, i realized that the userID seems to be assigned 0, fo the user object which is passed to the AddObject method. but i dont know why and how...
cemregoksu
Well, if userID is some kind of int, and is never assigned to, it will be 0.
Wonko the Sane
is it a problem for sql? and should i do something for it? how can i fix it?
cemregoksu
There is not enough information here (for me, anyway) to give you a definitive answer. I would suggest editing your original post with more information. That being said, in general, you should not (cannot) attempt to update the identity field of a SQL database. How is the update being done (direct UPDATE call, or stored procedure)? Find that code, and work backwards. That is where the fix will most likely be needed.
Wonko the Sane
Also, it is often the case that an INSERT call will return the value of the identity column (or an instantiated class) that represents, in your case, the userID generated by the database. The design of the database is probably going to be to big and complex a topic to discuss in detail on SO.
Wonko the Sane
+2  A: 

I'm not familiar with entity-framework, but for the curious this is the MS SQL command for enabling an insert on an identity column:

SET IDENTITY_INSERT tablename ON

I agree with Wonko to Sane, the problem is almost certainly in the AddToUsers method.

Jordan Reiter
+1 for the info, and +1 for agreeing with me. :)
Wonko the Sane