asp.net - IDENTITY_INSERT is set to off error -


I have a MVC web application with a table in the model that I would like to add I have the primary key set with other data fields , But every time I try to add to the table, I get the following error:

"Clear value for the identity column in the table 'TABLE_NAME' can not be inserted when the IDENTITY_INSERT closes I'm not sure. "

Why this problem is coming up, I have the primary key set as the identity and it is also set to auto increment in the Visual Studio table designer. Can I adjust the IDENTITY_INSERT parameter in the Table Designer in Visual Studio ?? Or there is another such issue which may be due to it.

UPDATE: @Brian - As far as I can tell, I'm not explicitly setting the value, here is the code that adds to the table (S).

  Add Viewer Public Zero AddViewer (ModelStateDictionary ModelState, User User) {var userToAdd = new UserRoles (); UserToAdd.Users = Users; If (String.IsNullOrEmpty (userToAdd.Users.Username)) {modelState.AddModelError ("noName", "Please enter the user name for the new viewer"); } // See if the committee member already exists {userToAdd = _db.UserRoles.First (ur = & gt; ur.Users.Username == userToAdd.Users.Username); ModelState.AddModelError ("userExists", "A viewer with that username is already present in the system"); Return; } Hold (exception e) {if (modelState.IsValid) {// appointed committee member role userToAdd.Role = "Viewer"; UserToAdd.Users = Users; // Add new committee member for User Rules and user related to _db.AddToUserRoles (userToAdd); _db.SaveChanges (); }}}}  

It appears that your code includes a specific value Trying is the primary key column defined as identity.

To avoid error - do not insert a value! If you are using Linq-to-SQL, click on the table in question in your visual designer, and take a look. Properties:

"Auto-built value should be" true "(which is not the default), and auto-sync should be" OnInstate "(again: not default ). Also, set the "primary key" to the correct, and to ensure that "server data type" is correct - int NOT NULL IDENTITY (or something like this).

If you sometimes need to override the default behavior (usually only in a clean-up script or one-off data manipulation), you can turn IDENTITY_INSERT on the table, for example After that, you can include any value in the Identity Card:

  SET IDENTITY_INSERT Enter your TableName (Identity column) values ​​on yourTableName (5555) SET IDENTITY_INSERT YourTableName OFF  


Comments