EF Code First giving me error Cannot insert explicit value for identity column in table 'People' when IDENTITY_INSERT is set to OFF.

Howard Pinsley picture Howard Pinsley · Jan 13, 2011 · Viewed 69k times · Source

I'm trying out Entity Framework 4's Code First (EF CodeFirst 0.8) and am running into a problem with a simple model that has a 1 <--> 0..1 relationship, between Person and Profile. Here's how they're defined:

public class Person
{
    public int PersonId { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime? DOB { get; set; }

    public virtual Profile Profile { get; set; }
}

public class Profile
{
    public int ProfileId { get; set; }
    public int PersonId { get; set; }
    public string DisplayName { get; set; }

    public virtual Person Person { get; set; }
}

The DB context looks like this:

public class BodyDB : DbContext
{
    public DbSet<Person> People { get; set; }   
}

I didn't define a DbSet for Profile because I consider People to be its aggregate root. When I try to add a new Person - even one without a Profile with this code:

public Person Add(Person newPerson)
{
    Person person = _bodyBookEntities.People.Add(newPerson);
    _bodyBookEntities.SaveChanges();
    return person;
}

I get the following error:

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

The newPerson object has a 0 for the PersonId property when I call People.Add(). The database tables are People and Profiles. PersonId is the PK of People and is an auto-increment Identity. ProfileId is the PK of Profiles and is an auto-incement Identity. PersonId is a non-null int column of Profiles.

What am I doing wrong? I think I'm adhering to all the EF Code First's convention over configuration rules.

Answer

Samidjo picture Samidjo · Oct 26, 2011

I get the following error: Cannot insert explicit value for identity column in table 'People' when IDENTITY_INSERT is set to OFF.

I think that the IDENTITY_INSERT is the Auto Increment functionality which is off. So, check the field PersonId in the database to see if it is an identity.

Besides, maybe this will fix your problem too.

[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int PersonId { get; set; }