How to define many to many with attributes in Entity Framework

匆匆过客 提交于 2019-12-13 20:53:10

问题


I try to model many to many relationship between Car and Employee where the info about when the car was used are held. So I need a class inbetween which will hold those additional attributes.

The SSCCE:

I have Person class:

  public class Person {
        public int Id { get; set}; 
  }

and a class Employee which derives from Person:

public class Employee : Person {
      public virtual ICollection<EmployeeCar> EmployeeCar { get; set; }
}

and a association classEmployeeCar which holds attributes dateFrom, dateTo:

public class EmployeeCar {
    [Key, Column(Order = 0)]
    public virtual Car Car { get; set; } 
    [Key, Column(Order = 1)]
    public virtual Employee Employee { get; set; }

    public DateTime DateFrom{ get; set; }
    public DateTime DateTo { get; set; }
}  

and finally class Car:

public class Car {
        public int Id { get; set; }
        public virtual ICollection<EmployeeCar>  EmployeeCar { get; set; }
    }

in ApplicationDbContext I hold:

    public DbSet<Person> Persons { get; set; }
    public DbSet<EmployeeCar> EmployeesCars { get; set; }
    public DbSet<Car> Cars { get; set; }

but when I run the database-update I get:

MyApp.EmployeeCar: : EntityType 'EmployeeCar' has no key defined. Define the key for this EntityType.
EmployeesCars: EntityType: EntitySet 'EmployeesCars' is based on type 'EmployeeCar' that has no keys defined.

How to fix that situation? How to tell Entity Framework that combination of Car and Employee is the key?


回答1:


You would need to add the ID properties themselves to the model definition -- EF can add foreign key properties automatically, but it probably doesn't like the idea of seeing navigation properties as keys.

public class EmployeeCar {
    [Key, Column(Order = 0)]
    public int CarId { get; set; }
    [Key, Column(Order = 1)]
    public int EmployeeId { get; set; }

    public virtual Car Car { get; set; }
    public virtual Employee Employee { get; set; }

    public DateTime DateFrom{ get; set; }
    public DateTime DateTo { get; set; }
}  

Create code first, many to many, with additional fields in association table



来源:https://stackoverflow.com/questions/30577738/how-to-define-many-to-many-with-attributes-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!