2012-02-18 69 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时,这种相等性不是很有用。你可以用不同的引用在内存中加载一个记录的多个实例,这样就不可能通过它们的引用来检查对象的相等性。这就是当检查等价值时玩和钥匙在这场比赛中扮演着主要角色。

相关问题