2014-01-09 40 views
10

爲了減少這種問題,一個簡單的版本,我已經創造了這個表:EF代碼第一:添加行表無標識的主鍵

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

注意,id字段不是身份領域。現在,如果我嘗試使用EF代碼第一次插入一行:

[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。任何線索或暗示歡迎。

+2

你嘗試刪除'[關鍵]'屬性? – hunter

+0

@hunter:是的,結果有相同的錯誤。我假設EF隱含地假設以'Id'結尾的列是關鍵。 – Andomar

+1

嘗試使用此DataAnotations選項'[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)]' –

回答

14

只需添加這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; } 
}