2012-02-18 68 views
5

我想顯示客戶信息。 然後我創建了一些類;客戶,交貨,訂單,OrderLine,產品和租賃DB。 rentalDB類設置5個DbSet的Product,Customer,Order,OrderLine和Delivery。 當我做UserController中與列表視圖,我不能顯示客戶信息,並採取錯誤:ASP.NET MVC 3 EntityType沒有定義密鑰

One or more validation errors were detected during model generation: 
System.Data.Edm.EdmEntityType: : EntityType 'OrderLine' has no key defined. Define the key for this EntityType. 
System.Data.Edm.EdmEntityType: : EntityType 'Delivery' has no key defined. Define the key for this EntityType. 
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �OrderLine� is based on type �OrderLine� that has no keys defined. 
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �Delivery� is based on type �Delivery� that has no keys defined. 

我不知道爲什麼這些企業需要的關鍵? 我不知道這個錯誤.. 你能幫我嗎?

--UserController.cs--

namespace MvcApplication2.Controllers 
{ 
public class UserController : Controller 
    { 
    // 
    // GET: /User/ 
    rentalDB _db = new rentalDB(); 

    public ActionResult Index() 
    { 
     var model = _db.Customer; 
     return View(model); 
    } 
    } 
} 

--Delivery.cs在模型folder--

namespace MvcApplication2.Models 
{ 
    public class Delivery 
    { 
    public int trackId { get; set; } 
    public String address { get; set; } 
    public String postCode { get; set; } 
    public decimal deliveryPrice { get; set; } 
    public DateTime deliveryDate { get; set; } 
    public DateTime returnDate { get; set; } 
    } 
} 

--OrderLine.cs在模型folder--

namespace MvcApplication2.Models 
{ 
    public class OrderLine 
    { 
    public int basketId { get; set; } 
    public int productId { get; set; } 
    public int quantity { get; set; } 
    } 
} 

回答

17

爲了使用實體框架,每個實體都需要一個密鑰。這就是EF如何跟蹤其緩存中的對象,將更新發布回底層數據存儲並將相關對象鏈接在一起。

此致對象已經有鑰匙,你只需要告訴他們的EF:當您使用ORM(對象關係映射)框架像NHibernate的或實體框架,它可以幫助你映射關係

namespace MvcApplication2.Models 
{ 
    public class Delivery 
    { 
    [Key] public int trackId { get; set; } 
    public String address { get; set; } 
    public String postCode { get; set; } 
    public decimal deliveryPrice { get; set; } 
    public DateTime deliveryDate { get; set; } 
    public DateTime returnDate { get; set; } 
    } 
} 
+0

這在特殊情況下適用於我。我在爲模型編寫代碼後添加了一個控制器,但沒有得到該錯誤。那時我意識到模型不是我想要的,意味着所有生成的視圖都非常錯誤,所以我刪除了控制器/視圖。然後,當我修復模型並添加控制器時,出現錯誤。在搞亂了一個小時之後,我添加了[Key],它工作。也許視覺工作室Mvc奇怪或緩存,不知道... – isitdanny 2014-04-25 02:05:18

0

數據庫到對象模型,你需要的東西可以讓你在內存中的對象和數據庫中的數據行之間建立一個有意義的關係,而這個東西是一個關鍵(NHibernate稱之爲id),通常這是RDBMS跟蹤的自然方式記錄使用主鍵(通常使用DB主鍵作爲對象的鍵) 當您使用==運算符檢查兩個對象是否相等時,您正在檢查這些對象具有相同的引用(或內存中的地址)。當你使用ORM時,這種相等性不是很有用。你可以用不同的引用在內存中加載一個記錄的多個實例,這樣就不可能通過它們的引用來檢查對象的相等性。這就是當檢查等價值時玩和鑰匙在這場比賽中扮演着主要角色。

相關問題