0
votes

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?

2
You should add your dbcontext, that will give us more idea as to whats wrong. Is Conference a table or view? Also, check the query that EF is creating while inserting using a profiler or in debug. It looks like ConferenceDetail is a view and EF tries to insert data into conferencedetail table for the same ID, however, that record already exists in conference table - Polynomial Proton

2 Answers

2
votes

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

1
votes

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.