简体   繁体   中英

How to define many to many with attributes in Entity Framework

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 class EmployeeCar 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM