c# - EF 代码优先 : Add row to table with a non-identity primary key

标签 c# sql-server entity-framework ef-code-first

为了将这个问题简化为一个简单的版本,我创建了这个表:

create table TestTable(id int primary key, descr varchar(50))

请注意,id 字段不是身份字段。现在,如果我尝试使用 EF Code First 插入一行:

[Table("TestTable")]
public class TestTable
{
    [Key]
    public int id { get; set; }
    public string descr { get; set; }
}

public class TestContext : DbContext
{
    public TestContext(string connectionString) : base(connectionString) {}
    public DbSet<TestTable> TestTables { get; set; }
}

static void Main()
{
    const string connectionString = "...";
    using (var db = new TestContext(connectionString))
    {
        db.TestTables.Add(new TestTable { id = 42, descr = "hallo" });
        db.SaveChanges();
    }
}

结果异常:

Cannot insert the value NULL into column 'id', table 'TestTable'; column does not allow nulls.

但是插入行的代码指定了id = 42。欢迎任何线索或提示。

最佳答案

只需添加此DataAnnotations [DatabaseGenerated(DatabaseGeneratedOption.None)] 和库

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

[Table("TestTable")]
public class TestTable
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int id { get; set; }
    public string descr { get; set; }
}

关于c# - EF 代码优先 : Add row to table with a non-identity primary key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21023050/

相关文章:

sql - 这种表结构最具扩展性的设计是什么

c# - 如何使用 Entity Framework 在 asp.net mvc 标识中添加新列

c# - Entity Framework ,获取选中项的周边项

c# - WebAPI 在返回 JSON 时正确序列化从抽象类型派生的类,但不序列化 XML

c# - 为什么要在 C# 中对 boolean 值使用 |= 运算符?

sql-server - SQL 服务器 2012 : Select xml with repeated and ungrouped set of elements

sql-server - SQL Server 作业无法识别 AWS CLI 命令

c# - 使用 Entity Framework 将 int 列映射到枚举属性

c# - 使用 WebRequests 下载 pdf 文件

c# - IdentityModel 中 TokenClient 的问题