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.
By default, SQL Server automatically inserts an increment value for an IDENTITY column, when the IDENTITY_INSERT parameter is set to OFF. If you don't need an explicit value for the IDENTITY column, remove the IDENTITY column from the component schema.
In this article, we will discuss the error “Cannot insert explicit value for identity column in table <table name> when IDENTITY_INSERT is set to OFF” as shown below. The error arises when the user has set “identity_insert” to “OFF”. Then tries to insert data into the primary key column of the table explicitly.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With