2013-10-29 69 views
0

我剛開始嘗試實體框架。我創建了一個表,如下所示:實體框架SaveChanges():主鍵列的值不在

CREATE TABLE WORK_EFFORT 
(
    K__ID BIGINT, 
    NAME NTEXT, 
    DESCRIPTION NTEXT 
) 

我還設置

K__ID 

是主鍵。

早在我的業務層,當我運行下面的代碼,

var db = new ENTERPRISE_context(); 

var workEffort = new WORK_EFFORT 
{ 
    K__ID = 1, 
    NAME = "merhaba, dünya", 
    DESCRIPTION = "merhaba, dünya" 
}; 
db.WORK_EFFORT_set.Add(workEffort); 

db.SaveChanges(); 

我得到一個

Cannot insert the value NULL into column 'K__ID', table 'ENTERPRISE.dbo.WORK_EFFORT'; column does not allow nulls. INSERT fails. 
The statement has been terminated. 

錯誤。 SQL事件探查揭示了以下RPC發送到SQL Server:

exec sp_executesql N'INSERT [dbo].[WORK_EFFORT]([NAME], [DESCRIPTION]) 
VALUES (@0, @1) 
SELECT [K__ID] 
FROM [dbo].[WORK_EFFORT] 
WHERE @@ROWCOUNT > 0 AND [K__ID] = scope_identity()',N'@0 nvarchar(max) ,@1 nvarchar(max) ',@0=N'merhaba, dünya',@1=N'merhaba, dünya' 

爲了您的信息,對於上述支持代碼是像這樣:

namespace Web.Models 
{ 
    public partial class WORK_EFFORT 
    { 
     public long K__ID { get; set; }  
     public string NAME { get; set; } 
     public string DESCRIPTION { get; set; } 
    } 
} 

namespace Web.Models.Mapping 
{ 
    public partial class WORK_EFFORT_map : EntityTypeConfiguration<WORK_EFFORT> 
    { 
     public WORK_EFFORT_map() 
     { 
      this.HasKey(t => t.K__ID); 

      this.ToTable("WORK_EFFORT"); 

      this.Property(t => t.K__ID).HasColumnName("K__ID"); 
      this.Property(t => t.NAME).HasColumnName("NAME"); 
      this.Property(t => t.DESCRIPTION).HasColumnName("DESCRIPTION"); 
     } 
    } 
} 

namespace Web.Models 
{ 
    public partial class ENTERPRISE_context : DbContext 
    { 
     static ENTERPRISE_context() 
     { 
      Database.SetInitializer<ENTERPRISE_context>(null); 
     } 

     public ENTERPRISE_context() : base("Name=ENTERPRISE_context") { } 

     public DbSet<WORK_EFFORT> WORK_EFFORT_set { get; set; } 

     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 
      modelBuilder.Configurations.Add(new WORK_EFFORT_map()); 
     } 
    } 
} 

回答

2

根據您的SQL INSERT語句EF認爲K__ID是一個身份這是錯誤的列。 在映射的以下行中指定HasDatabaseGeneratedOption與None:

Property(t => t.K__ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);