且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架错误:无法在表中插入标识列的显式值

更新时间:2023-01-22 09:10:40

我以前遇到过。此错误意味着您正在尝试将数值显式分配给数据库自动分配的列。



建议:
更新您的edmx文件以反映任何更改你可能已经在数据库中做了。
如果数据库自动分配该值,则应在该属性下的设计器文件中看到IsDbGenerated = true属性。如果不在,可以手动添加。


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();

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.