EF Foreign Key using Fluent API

c# entity-framework

Question

My models are shown here. For the vehicle and the driver, I have a one-to-one mapping. Prior to mapping the driver to the car, I will design 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; }
}

To maintain the id of the car the driver is driving, I want to use the VehicleId attribute in the Driver class.

The following Fluent API code was created by me:

modelBuilder.Entity<Vehicle>()
            .HasRequired(d => d.Driver)
            .WithRequiredPrincipal();

However, it adds a new column called Vehicle VehicleId to the Drivers database and maps it to the VehicleId column in the Vehicle table. I want the Driver table's VehicleId to map.

I'm also fresh to EF and the Fluent API. Choosing between WithRequiredDependent and WithRequiredPrincipal is quite difficult for me. I'd be grateful if you could sum it up simply. Thanks.

1
14
1/20/2014 8:36:57 AM

Accepted Answer

This phrase:

public int VehicleId { get; set; }

via means of code-conventions is indicating to EF that you want a foreign key inDriver directing toVehicle .

You can inform EF that you desire a 1:1 relationship by doing the following.Driver to Vehicle :

public virtual Vehicle Vehicle { get; set; }

Both should be eliminated, and you should continue using your Fluent API settings.

WithRequiredPrincipal vs. WithRequiredDependent in relation to:

You are defining a necessary connection betweenVehicle and Driver with guidance fromVehicle to Driver therefore: Vehicle 1 -> 1.Driver

(The main is the vehicle.Driver since the navigation property is situated in the dependentVehicle and indicatingDriver .)

modelBuilder.Entity<Vehicle>()
            .HasRequired(d => d.Driver)
            .WithRequiredDependent();

You are defining a necessary connection betweenVehicle and Driver with guidance fromDriver to Vehicle , thus:Vehicle 1 <— 1Driver

(Vehicle is reliant on andDriver given that the navigational property is situated inDriver directing toVehicle .)

These two are comparable:

modelBuilder.Entity<Vehicle>()
            .HasRequired(v => v.Driver)
            .WithRequiredPrincipal();

modelBuilder.Entity<Driver>()
            .HasRequired(d => d.Vehicle)
            .WithRequiredDependent();
24
12/20/2018 8:05:38 AM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow