我正在尝试使用Entity Framework 4的Code First(EF CodeFirst 0.8),并且遇到一个简单模型的问题,该模型在之间具有1<-> 0..1关系。人和个人资料。定义方式如下:
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; } }数据库上下文如下:
public class BodyDB : DbContext { public DbSet<Person> People { get; set; } }我没有定义 DbSet 用于个人资料,因为我认为人是其总根。当我尝试添加新的 Person 时-即使没有 Profile 的人也使用此代码:
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; }我收到以下错误:
当IDENTITY_INSERT设置为OFF时,不能为表'People'中的身份列插入显式值。
Cannot insert explicit value for identity column in table 'People' when IDENTITY_INSERT is set to OFF.
newPerson 对象的 0 当我呼叫 People.Add()时, PersonId 属性的code>。数据库表是人和个人资料。 PersonId 是 People 的PK,并且是一个自动递增的身份。 ProfileId 是 Profiles 的PK,并且是自动递增的身份。 PersonId 是个人资料的非空int列。
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.
我在做什么错?我认为我遵守所有EF Code First的配置规则约定。
What am I doing wrong? I think I'm adhering to all the EF Code First's convention over configuration rules.
推荐答案
I出现以下错误:当IDENTITY_INSERT设置为OFF时,无法在表'People'中为身份列插入显式值。
I get the following error: Cannot insert explicit value for identity column in table 'People' when IDENTITY_INSERT is set to OFF.
我认为IDENTITY_INSERT是关闭的自动增量功能。 因此,请检查数据库中的PersonId字段是否为身份。
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; }更多推荐
EF代码首先给我错误当IDENTITY
发布评论