为了将这个问题简化为一个简单的版本,我创建了这个表:
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/