What you're looking for is a mutually optional 1:1 association between independent entities (more exactly: 0..1-0..1). As I explained here, EF isn't really helpful here, but there are some options.
The first option is to settle with a 1-0..1 association, which is fully supported by EF. But either Car
or Driver
should have a primary key that's also a foreign key to the other entity. From what I read, this is not what you want. You want both entities to be able to exist independent of the other.
So the only option is, as you describe, introducing a third entity, aka a junction class. Now, Entity Framework only supports this for many-to-many associations, not for 1:1. So you'll have to map the association as many-to-many, but take some special measures to prevent duplicate associations on both ends.
To achieve that, this is what I came up with:
public class Car
{
public Car()
{
CarDrivers = new HashSet<CarDriver>();
}
public int CarId { get; set; }
public string Name { get; set; }
public virtual ICollection<CarDriver> CarDrivers { get; set; }
}
public class Driver
{
public Driver()
{
CarDrivers = new HashSet<CarDriver>();
}
public int DriverId { get; set; }
public string Name { get; set; }
public virtual ICollection<CarDriver> CarDrivers { get; set; }
}
public class CarDriver
{
[Key, Column(Order = 0), Index(IsUnique = true)]
public int CarId { get; set; }
[Key, Column(Order = 1), Index(IsUnique = true)]
public int DriverId { get; set; }
public Car Car { get; set; }
public Driver Driver { get; set; }
}
This is an explicit many-to-many association (i.e. having a visible junction class), but restricted to 1 at both ends by the unique indexes on both foreign keys in CarDriver
.
So at least at the database side, the proper multiplicity of the association is enforced. However, in your code, nothing stops you from adding more than one CarDriver
to the CarDrivers
collections. This will throw an ugly database constraint error, so you'll have to guard this with custom validation.