ASP.NET MVC 3 EntityType 没有定义键

标签 asp.net asp.net-mvc-3 entity

我想显示客户信息。 然后我创建了一些类;客户、交货、订单、订单行、产品和租赁数据库。 RentalDB 类设置了 5 个 DbSet:Product、Customer、Order、OrderLine 和 Delivery。 当我使用 ListView 制作UserController时,无法显示客户信息,并且出现错误:

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.

我不知道为什么这些实体需要 key ? 我不知道这个错误.. 你能帮我吗?

--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);
    }
  }
}

--Models文件夹中的Delivery.cs--

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; }
  }
}

--Models 文件夹中的 OrderLine.cs--

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

最佳答案

为了使用 Entity Framework ,每个实体都需要一个 key 。这就是 EF 跟踪其缓存中的对象、将更新发布回底层数据存储并将相关对象链接在一起的方式。

你的对象已经有了键,你只需要把它们告诉 EF:

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; }
  }
}

关于ASP.NET MVC 3 EntityType 没有定义键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9344244/

相关文章:

ASP.NET 页面特定配置

c# - MVC 3 beta + Dependency Resolver + Unity = 有​​问题

c# - .NET 数据模型显示为 XML 而不是图表

html - XUL:如何呈现特殊的 html 实体(复制、交易、deg...)?

asp.net - 当最后一个文件下载 block 发送时,让 IIS 通知 ASP.NET

asp.net - 谁在生产应用程序中实际使用DataGrid/GridView/FormView/etc?

C# DateTime求值问题

C# 数据库访问 : Best method to use for getting data

database - 数据库中的对象和实体有什么区别?

c# - 使用选择和参数插入