halterdev
halterdev

Reputation: 343

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?

Upvotes: 0

Views: 3005

Answers (2)

Developer
Developer

Reputation: 6450

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

Upvotes: 2

Sibele Lima
Sibele Lima

Reputation: 206

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.

Upvotes: 1

Related Questions