当主键/标识列为空时,如何使用EF创建新记录?

时间:2013-07-30 09:09:06

标签: c# entity-framework entity-framework-4.1 entity-framework-5

我们正在使用Entity Framework 5在SQL Server 2012数据库中创建新的答复记录。

这是答案类:

public class Answer
{
    public int? AnswerId { get; set; }
    public string Text { get; set; }

}

SQL:

CREATE TABLE Answer (
   [AnswerId] INT IDENTITY (1, 1) NOT NULL,
   ...
   ...
   CONSTRAINT [PK_Answer] PRIMARY KEY CLUSTERED ([AnswerId] ASC)

这是EF Mapping:

public class AnswerMap : EntityTypeConfiguration<Answer>
{
    public AnswerMap()
    {
        // Primary Key
        this.HasKey(t => t.AnswerId);

        // Identity
        this.Property(t => t.AnswerId)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

    }
}

但是当在AnswerId中插入一个带有null的新Answer时,我们仍然会得到以下内容:

关键字段'AnswerId'的值不能为null。 “答案”类型上定义的关键字段需要非空值。

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=The key field 'AnswerId' cannot have a value of null. A non-null value is required for the key fields defined on type 'Answer'.
  Source=System.Data.Entity
  StackTrace:
       at System.Data.Objects.ObjectStateManager.CreateEntityKey(EntitySet entitySet, Object entity)
       at System.Data.Objects.ObjectContext.AttachSingleObject(IEntityWrapper wrappedEntity, EntitySet entitySet, String argumentName)
       at System.Data.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach)
       at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach)
       at System.Data.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
       ....

那么如何添加我的POCO课程呢?我唯一能做的就是将AnswerId设置为null,因为它是一个数据库生成的数字。但是当我这样做时,EF抱怨它是空的,即使我指定它是EF的标识列。

1 个答案:

答案 0 :(得分:2)

将您的Answer课程更改为:

public class Answer
{
    public int AnswerId { get; set; }
    public string Text { get; set; }
}

数据库插入后,主键值将由Entity Framework自动设置。

不要自己修改AnswerId,只需保留即可。对于尚未插入的对象,它将为零。