0

我们正在使用 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 映射:

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 的新答案时,我们仍然会得到以下信息:

关键字段“AnswerId”的值不能为空。在“Answer”类型上定义的关键字段需要非空值。

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 也会抱怨它为空。

4

1 回答 1

2

改变你的Answer类是这样的:

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

主键值将在数据库插入后由实体框架自动设置。

不要自己修改 AnswerId,保持不变。对于尚未插入的对象,它将为零。

于 2013-07-30T09:20:37.120 回答