ASP.NET MVC 3 EntityType has no key defined

前端 未结 2 1640
南笙
南笙 2021-01-12 18:33

I want to display customer information. Then I created some classes; Customer, Delivery, Order, OrderLine, Product, and rentalDB. rentalDB class sets 5 DbSet of Product, Cus

相关标签:
2条回答
  • 2021-01-12 19:16

    In order to use the entity framework, every entity needs a key. This is how EF tracks objects in its cache, posts updates back to the underlying data store, and links related objects together.

    Yours objects already have keys, you just need to tell the EF about them:

    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 讨论(0)
  • 2021-01-12 19:23

    When you use an ORM (object-relational mapper) framework like NHibernate or Entity framework that helps you map a relational database to an object model you need something that will let you make a meaningful relation between your objects in memory and rows of data in your database and that thing is a key (id as NHibernate call it) and usually that's the natural way that RDBMS track records using a Primary key (usually you use DB primary key as the key of your object) When you check to see if two objects are equal using == operator you are checking that those objects have the same reference (or address in memory). This kind of equality is not very helpful when you are using an ORM .You can load multiple instances of a record in memory with different references so that it's impossible to check the equality of objects by their references .That's when checking equality by value come into play and keys have the main role in this play.

    0 讨论(0)
提交回复
热议问题