在EntityFramework, Version=6.0.0.0,維護一個現有項目,修改代碼后,編譯正常。但運行系統,竟然報發生異常,加斷點跟蹤發現拋出“One or more validation errors were detected during model generation”
由於對EF不夠熟悉。所以網上搜索了一番,提示:原因是因為我在寫實體類的時候沒有為實體類中的屬性聲明一個主鍵,即用[key]特性標注在屬性上,這樣DbContext才能為我們在數據庫上找到對應的主鍵。由於是現有項目進行的修改,我找到自己的實體類,和之前的類對比,並沒有這個屬性。
又查了一些資料如下:
主鍵:在數據表中是指記錄的唯一標識符。
而在EF模型中的主鍵有如下規則:
- 明確指定某個字段為模型的主鍵(通過注解和Fluent API)
- 如果沒有明確指定,那么按照約定將名為
Id
或者類名Id
這個屬性設置為主鍵。 - 如果上述都沒有滿足,EF執行時會報錯。
在EF中指定主鍵的映射關系,有以下幾種方法:
2.通過Fluent API設置主鍵(重寫DbContext的
-
約定
Id
和類名Id
約定例子:
class Car { public string CarId { get; set; }//主鍵 public string Make { get; set; } public string Model { get; set; } }
-
顯式設置
1.通過注解設置主鍵
class Car { [Key] public string LicensePlate { get; set; } public string Make { get; set; } public string Model { get; set; } }
2.通過Fluent API設置主鍵(重寫DbContext的OnModelCreating方法
)
class MyContext : DbContext { public DbSet<Car> Cars { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Car>() .HasKey(c => c.LicensePlate); } } class Car { public string LicensePlate { get; set; } public string Make { get; set; } public string Model { get; set; } }
-
顯式設置聯合主鍵(重寫DbContext的
OnModelCreating方法
)
class MyContext : DbContext { public DbSet<Car> Cars { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Car>() .HasKey(c => new { c.State, c.LicensePlate }); } } class Car { public string State { get; set; } public string LicensePlate { get; set; } public string Make { get; set; } public string Model { get; set; } }
-
單獨的類來管理配置,繼承EntityTypeConfiguration<TEntity>類實現
在OnModelCreating方法中,如果有很多實體的話,OnModelCreating方法管理很麻煩,可以通過繼承System.Data.Entity.ModelConfiguration命名空間中的
EntityTypeConfiguration<TEntity>類來實現
public class xxx: EntityTypeConfiguration<Student> { public xxx() { this.ToTable("StudentInfo"); this.HasKey<int>(s => s.StudentKey); } }