Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework error: Cannot insert explicit value for identity column in table

I'm getting this error on EF.

Cannot insert explicit value for identity column in table 'GroupMembers_New' when IDENTITY_INSERT is set to OFF.

The column on the Db is identity increment and on the EF design file, StoreGeneratedPattern is identity as well. Seems like EF is trying to insert 0 every time I try to save.

Some suggestions says ID is reserved on tables or drop the table and rerun the scripts.

Any ideas?

Here's some code:

GroupMember groupMember = new GroupMember();             groupMember.GroupId = group.Id;             groupMember.UserId = (new UserId(group.Owner));             //groupMember.Id = _groupContext.GroupMembers.Count();             group.GroupMembers.Add(groupMember);              _groupContext.SaveChanges(); 

database

EF Designer

like image 958
HoBa Avatar asked Jun 23 '12 22:06

HoBa


People also ask

What is meant by this error message in the SQL query window Cannot insert explicit value for identity column in Table tracks?

In this article, we will discuss the error “Cannot insert explicit value for identity column in table <table name> when IDENTITY_INSERT is set to OFF” as shown below. The error arises when the user has set “identity_insert” to “OFF”. Then tries to insert data into the primary key column of the table explicitly.


2 Answers

I have run into this before. This error means you are trying to assign a value explicitly to a column where the database automatically assigns it.

Suggestion: Update your edmx file to reflect any changes you may have made in the database. If the database automatically assigns the value, you should see the "IsDbGenerated=true" attribute in your designer file under that property. If it's not there, you can add it manually.

like image 100
ems305 Avatar answered Sep 21 '22 20:09

ems305


Try this:

using System.ComponentModel.DataAnnotations.Schema; [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public decimal Identity_Col { get; set; } 

The Entity Framework class file adds these lines of code to the Identity column.

like image 37
thomas Avatar answered Sep 20 '22 20:09

thomas