如何使用 Entity Framework 中的属性定义多对多

How to define many to many with attributes in Entity Framework

我尝试对 CarEmployee 之间的多对多关系建模,其中保存了有关何时使用汽车的信息。所以我需要一个 class 中间来保存这些额外的属性。

SSCCE:

我有 Person class:

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

和 class Employee 派生自 Person:

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

和一个关联 classEmployeeCar,其中包含属性 dateFromdateTo

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

最后 class Car:

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

ApplicationDbContext我持有:

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

但是当我 运行 database-update 我得到:

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.

如何解决这种情况?如何告诉 Entity Framework CarEmployee 的组合是关键?

您需要将 ID 属性本身添加到模型定义中——EF 可以自动添加外键属性,但它可能不喜欢将导航属性视为键的想法。

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