简体   繁体   中英

Entity Framework 'Cannot insert explicit value for identity column' error

I understand what the error message is saying. I'm just not sure why it is saying it. My table has an Identity and it is set to auto-increment, yet when I go to save an entity I get the following error:

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

I'm using a code-first approach and my Conference entity looks like this:

public class Conference
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public int DugoutId { get; set; }
    public int ConferenceDetailsId { get; set; }

    [ForeignKey("Id")]
    public virtual Dugout Dugout { get; set; }
    [ForeignKey("Id")]
    public virtual ConferenceDetail ConferenceDetail { get; set; }
}

When I am going to save the Conference, the values are as follows:

Id: 0
DugoutId: 15
ConferenceDetailsId: 1
Dugout: null
ConferenceDetail: null

Any ideas why this won't save?

The [ForeignKey] attibutes are pointing to wrong property for Dugout and ConferenceDetails. Should be ForeignKey("DugoutId") and ForeignKey("ConferenceDetailsId").

Are you using code first or is the code being generated automatically? Depending on what you are doing, there might be a mismatch between the model and the database. You can try and use a profiler to know exactly what EF is trying to do. This thread could help you as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM