How to define many to many with attributes in Entity Framework
I am trying to model many of the relationships between Car
and Employee
where information is stored about when the car was used. So I need a class in between that will contain these additional attributes.
SSCCE:
I have a Person
class:
public class Person {
public int Id { get; set};
}
and a class Employee
that comes from Person
:
public class Employee : Person {
public virtual ICollection<EmployeeCar> EmployeeCar { get; set; }
}
and the association class EmployeeCar
that contains 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 the class Car
:
public class Car {
public int Id { get; set; }
public virtual ICollection<EmployeeCar> EmployeeCar { get; set; }
}
in ApplicationDbContext
I am sticking with:
public DbSet<Person> Persons { get; set; }
public DbSet<EmployeeCar> EmployeesCars { get; set; }
public DbSet<Car> Cars { get; set; }
but when i run 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 this situation? How do I determine the Entity Framework what combination is Car
and Employee
is the key?
source to share
You will need to add the identity properties themselves to the model definition - EF can automatically add foreign key properties, 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 the association table
source to share