2012-02-28 84 views
1

我收到以下錯誤,而使用POCO實體寬度EF模型生成過程中檢測到EF代碼第一個問題NO關鍵字中定義

一個或多個驗證錯誤: System.Data.Edm.EdmEntityType:的EntityType「品牌'沒有定義關鍵字 。定義此EntityType的關鍵字。 System.Data.Edm.EdmEntitySet:EntityType:EntitySet'Brand'基於 ,其類型'Brand'沒有定義鍵。

POCO

public class Brand 
    { 
     //[Key] 
     public int BrandId { get; set; } 
     public String BrandName { get; set; } 
     public String CompanyName { get; set; } 
     public Int32 CountryId { get; set; } 
     public String Description { get; set; } 
    } 

DBConetxt

public class DBContext : DbContext 
    { 
     public DBContext() 
      : base("DBContext") 
     { } 


     public DbSet<Brand> Brand { get; set; } 
     public DbSet<Country> Country { get; set; } 

     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 
      modelBuilder.Entity<Brand>().ToTable("dbo.Brand"); 
      modelBuilder.Entity<Country>().ToTable("dbo.Country"); 
      base.OnModelCreating(modelBuilder); 
     } 
    } 

DB表

BrandId int 
BrandName varchar 
CompanyName varchar 
CountryId int 
Description varchar 
CreatedBy int 
CreatedDate datetime 
ModifiedBy int 
ModifiedDate datetime 

使用

DBContext o = new DBContext(); 
return o.Brand.ToList(); 

如果[Key]註釋與POCO一起使用來指示pk,那麼它工作正常,但我不想在POCO中使用任何依賴類。

任何建議???

謝謝

+0

再次,品牌具有Country表的FK屬性。使用MVC創建新品牌時,我需要顯示國家列表作爲下拉列表。請建議我最好的方法來創建品牌實體以實現這種情景? – Paul 2012-02-28 14:33:51

+0

您使用的是什麼版本的實體框架?如果您使用4.1+(http://msdn.microsoft.com/en-us/library/hh161541(v=vs.103).aspx) – 2012-02-28 15:03:27

回答

2

您可以使用流暢的API配置PK。您不必顯式指定數據庫模式爲dbo

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Brand>().ToTable("Brand"); 
     modelBuilder.Entity<Brand>().HasKey(b => b.BrandId); 

     modelBuilder.Entity<Country>().ToTable("Country"); 
     base.OnModelCreating(modelBuilder); 
    } 

您還可以在Brand POCO定義的導航屬性Country

public class Brand 
{ 
    public int BrandId { get; set; } 
    public String BrandName { get; set; } 
    public String CompanyName { get; set; } 
    public Int32 CountryId { get; set; } 

    public virtual Country Country {get; set; } 

    public String Description { get; set; } 
} 

Action方法

public ActionResult Create() 
    { 
     ViewData["Countries"] = new SelectList(db.Country.ToList(), 
       "CountryId", "CountryName"); 

     return View(); 
    } 

如果是視圖

@Html.DropDownListFor(model => model.CountryId, 
      (IEnumerable<SelectListItem>)ViewData["Countries"], "-") 
+0

感謝Eranga,BrandId應該被視爲您的關鍵。你的解決方案已經奏效Eranga,EF做所有動態映射類的東西。它會造成性能開銷?你可以在使用EF時建議一些性能改進提示嗎? – Paul 2012-02-28 15:42:44

+0

@Paul開銷只有一次操作。你**的開銷**不是基於事實。測試是否有顯着的開銷。 – Eranga 2012-02-28 15:48:11