Reputation: 311
ASP.NET MVC and I got an issue that I don't know how to solve
I have a Vehicle class in model
VehicleId
Register
.... Etc
And a Driver class
DriverId
FirstName
LastName
I want to create a new table in order to control of what vehicle have a Driver where each Vehicle cannot have more than one Driver
I think of creating a table DriverVehicle with the key from Vehicle and Driver. Any help related with this would be a big help. I am working with ASP.NET MVC and EF.
Upvotes: 1
Views: 294
Reputation: 109079
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.
Upvotes: 2
Reputation: 3926
Add DriverId as a foreign column in Vehicle table and add virtual list of Vehicles for a driver. So each vehicle will have single driver and each driver can drive many vehicles.
Vehicle Class
public virtual Driver Driver { get;set; }
public virtual int DriverId { get;set; } //make it null if you think some vechile dont have driver
Driver Class
public virtual IList<Vehicle> Vehicles { get;set; }
Upvotes: 0