[英]EF Code First: Add row to table with a non-identity primary key
為了將此問題簡化為簡單版本,我創建了此表:
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();
}
}
結果是一個例外:
無法將值NULL插入列'id',表'TestTable'; 列不允許空值。
但是插入行的代碼指定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; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.