[英]Entity Framework Non Identity - Cannot insert the value NULL into column 'ID'
I have a table with a primary Key of ID, this field is not an identity column. 我有一个主ID为ID的表,该字段不是标识列。 My migration for Entity Framework 6 is
我对Entity Framework 6的迁移是
CreateTable(
"dbo.Action",
c => new
{
ID = c.Int(nullable: false, identity: false),
ActionName = c.String(maxLength: 50),
})
.PrimaryKey(t => t.ID);
This all looks fairly straight forward to me. 这一切看起来都很直接。 Then I have a method to seed some data:
然后我有一个方法来播种一些数据:
public static void Seed(this DbSet<Action> entitySet)
{
MainContext dbCtx = DataRepositoryBase<Action>.GetContext(entitySet) as MainContext;
if (dbCtx != null)
{
entitySet.Add(new Action()
{
ID = 1,
ActionName = "Test"
});
}
}
It's at the this point I get an error 就在这时我得到了一个错误
"Cannot insert the value NULL into column 'ID', table 'dbo.Action'; column does not allow nulls. INSERT fails.\\r\\nThe statement has been terminated"
“无法将值NULL插入列'ID',表'dbo.Action';列不允许空值.INSERT失败。\\ r \\ n语句已终止”
As you can see I am clearly providing an value for the ID column. 如您所见,我显然为ID列提供了一个值。 My suspicion is that Entity Framework is expecting the ID to be an Identity column
我怀疑实体框架期望ID是一个Identity列
The Entity class is very simple Entity类非常简单
[DataContract]
public class Action
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string ActionName { get; set; }
}
Your migration only creates the table in the database but doesn't tell Entity Framework the the ID property is not an IDENTITY
column. 您的迁移仅在数据库中创建表,但不会告知实体框架ID属性不是
IDENTITY
列。 EF picks the property called ID if you do not tell it which property to use as the primary key, but you also need to tell EF that it's not an IDENTITY column, do this using the DatabaseGenerated
attribute: 如果您没有告诉它使用哪个属性作为主键,EF会选择名为ID的属性,但您还需要告诉EF它不是IDENTITY列,使用
DatabaseGenerated
属性执行此操作:
[DataContract]
public class Action
{
[DataMember]
[Key] //This isn't technically needed, but I prefer to be explicit.
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }
[DataMember]
public string ActionName { get; set; }
}
The error is due to the fact that fields name Id are supposed to be primary key and identity. 该错误是由于字段名称Id应该是主键和标识这一事实。
When EF generate insert statement does not generate value for that field. 当EF生成insert语句时,不会为该字段生成值。
You can fix it using 你可以用它修复它
[DataContract]
public class Action
{
[DataMember]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }
[DataMember]
public string ActionName { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.