c# - Entity Framework 非标识 - 无法将值 NULL 插入列 'ID'

标签 c# sql-server entity-framework primary-key identity

我有一个主键为ID的表,这个字段不是标识列。我对 Entity Framework 6 的迁移是

 CreateTable(
   "dbo.Action",
    c => new
    {
       ID = c.Int(nullable: false, identity: false),
       ActionName = c.String(maxLength: 50),
    })
    .PrimaryKey(t => t.ID);

在我看来,这一切都相当简单。然后我有一种方法来播种一些数据:

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"
            });                
    }
}

此时我得到一个错误

"Cannot insert the value NULL into column 'ID', table 'dbo.Action'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated"

如您所见,我清楚地为 ID 列提供了一个值。我怀疑 Entity Framework 期望 ID 是身份列

实体类很简单

[DataContract]
public class Action
{
    [DataMember]
    public int ID { get; set; }

    [DataMember]
    public string ActionName { get; set; }
}

最佳答案

您的迁移仅在数据库中创建表,但不会告诉 Entity Framework ID 属性不是 IDENTITY 列。如果您不告诉 EF 将哪个属性用作主键,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; }
}

关于c# - Entity Framework 非标识 - 无法将值 NULL 插入列 'ID',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33737319/

相关文章:

c# - 从 F# 访问 C# WPF

sql-server - 无法连接到SQL Server,错误:0-无法建立连接,因为目标计算机主动拒绝了它

Sql Select Statement Issue in order by

sql - 获取 SQL Server 中特定的 XML 子节点

linq - 使用 linq 和 Entity Framework 按值范围分组

c# - 如何在 EF 6 中对字符串类型的字段创建唯一约束?

c# - 我无法在未安装 SqlServer Express 的计算机上建立 Sql Server localdb 连接

c# - 请求中对象的值在wcf服务中始终为null

entity-framework - Entity Framework 是否将分配的值与原始值进行比较以确定 IsModified 标志?

C#6 : nameof() current property in getter/setter