我们正在使用 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 也会抱怨它为空。