I have read a lot of related questions about this topic but none of them seemed to address my problem, so please bear with me. I am new to EF and trying to establish the following relationship, in ASP .NET MVC, using EF6:
I need to have two permanent tables, Drivers and Cars. I now need to create a relationship between these tables when a Driver is associated to a Car. But one Driver can only be assigned to one Car.
A Driver may not always be associated to a Car and vice-versa and I want to maintain both tables even if there isn't always an association between them, so that is why I believe I need to have an additional table exclusively to make this connection. Which I think will create a 1:1:1 relationship between these classes.
Below is the model for my POCO classes.
Models
public class Driver
{
public int DriverID { get; set; }
public string Name { get; set; }
//other additional fields
public DriverCar DriverCar { get; set; }
}
public class Car
{
public int CarID { get; set; }
public string Brand { get; set; }
//other additional fields
public DriverCar DriverCar { get; set; }
}
public class DriverCar
{
public int DriverCarID { get; set; }
public int DriverID { get; set; }
public Driver Driver { get; set; }
public int CarID { get; set; }
public Car Car { get; set; }
}
I have tried configuration the relationships using Fluent API but I believe I am doing it completly wrong since I have got errors such as:
Introducing FOREIGN KEY constraint 'FK_dbo.DriverCar_dbo.Car_CarId' on table 'DriverCar' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors.
Fluent Api
modelBuilder.Entity<DriverCar>()
.HasRequired(a => a.Driver)
.WithOptional(s => s.DriverCar)
.WillCascadeOnDelete(false);
modelBuilder.Entity<DriverCar>()
.HasRequired(a => a.Car)
.WithOptional(s => s.DriverCar)
.WillCascadeOnDelete(false);
I am really not sure if I am missing something or if there is some better approach to handle this situation and I would appreciate so much if someone can give me some feedback on how to solve this.
Update
Just found an interesting answer here: Is it possible to capture a 0..1 to 0..1 relationship in Entity Framework? Which I believe is exactly what I want: a 0..1 to 0..1 relationship. But all the mentioned options seem too complex and I'm not quite sure which one is the best or how to even correctly implement them.
Are these type of relationships supposed to be so hard to implement in EF? For example, I tried Option 1 but it created a 0..1 to many relationship from both tables - Driver to Car and Car to Driver. How am I suppose to create an unique association between them then?