Here are my models. I have one to one mapping for Vehicle and Driver. I will have the vehicle created first and then map the driver to the vehicle.
public class Driver
{
public int Id { get; set; }
public String Name { get; set; }
public int VehicleId { get; set; }
public virtual Vehicle Vehicle { get; set; }
}
public class Vehicle
{
public int Id { get; set; }
public String Name { get; set; }
public virtual Driver Driver { get; set; }
public int VehicleGroupId { get; set; }
public virtual VehicleGroup Vehicles { get; set; }
}
I want to use VehicleId property in Driver class to keep id of vehicle the driver is driving.
I've written the following Fluent API code:
modelBuilder.Entity<Vehicle>()
.HasRequired(d => d.Driver)
.WithRequiredPrincipal();
But it creates a new column in Drivers table - Vehicle_VehicleId and maps it to the VehicleId on Vehicle table. I want the VehicleId of Driver table to map.
Also, i'm brand new to EF and Fluent API. I find it extremely confusing choosing between WithRequiredDependent and WithRequiredPrincipal. Would be glad if you can describe it in simple words. Thanks.
This line:
public int VehicleId { get; set; }
is telling EF, through code-conventions, that you want a foreign key in Driver
pointing to Vehicle
.
The following is telling EF that you want a 1:1 relationship from Driver
to Vehicle
:
public virtual Vehicle Vehicle { get; set; }
You should remove both and stick with your Fluent API configuration.
Regarding WithRequiredPrincipal vs. WithRequiredDependent:
You are specifying a compulsory relationship between Vehicle
and Driver
, with navigation from Vehicle
to Driver
, thus: Vehicle 1 --> 1 Driver
(Vehicle is the principal and Driver
the dependent, since the navigation property is located in Vehicle
and pointing to Driver
.)
modelBuilder.Entity<Vehicle>()
.HasRequired(d => d.Driver)
.WithRequiredDependent();
You are specifying a compulsory relationship between Vehicle
and Driver
, with navigation from Driver
to Vehicle
, thus: Vehicle
1 <-- 1 Driver
(Vehicle
is the dependent and Driver
the principal, since the navigation property is located in Driver
pointing to Vehicle
.)
These two are analogous:
modelBuilder.Entity<Vehicle>()
.HasRequired(v => v.Driver)
.WithRequiredPrincipal();
modelBuilder.Entity<Driver>()
.HasRequired(d => d.Vehicle)
.WithRequiredDependent();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With