pmulders pmulders - 1 year ago 76
C# Question

Realize Entity Framework one-to-one relation

I am trying to realize a one-to-one relation in Entity Framework with Code First. I want to create an Airplane table which has a FlightPlan.


public class Airplane
public int AirplaneId { get; set; }
public int Capacity { get; set; }
public AirplaneStatus AirplaneStatus { get; set; }
public int AmountOfPassengers { get; set; }
public int AirfieldId { get; set; }

public virtual FlightPlan FlightPlan { get; set; }


public class FlightPlan
public int AirplaneId { get; set; }
public int AirfieldFrom { get; set; }
public int AirfieldTo { get; set; }
public int AmountOfPassengers { get; set; }

public virtual Airplane Airplane { get; set; }

When i initialize these classes with Migrations the following table structure is created:

enter image description here

After i manage to create an Airplane with a FlightPlan, which takes some workarounds, the Airplane doesn't have a Flightplan no matter what i try.

enter image description here

enter image description here

How can i solve this?


For testing purposes i add a FlightPlan to every updated Airplane. After fixing this a route is created for adding a Flightplan. The code is:

var airplane = _context.Airplanes.Find(model.AirplaneId);
var flightplan = new FlightPlan() { AirfieldFrom = 1, AirfieldTo = 2, AmountOfPassengers = 30 };
airplane.FlightPlan = flightplan;

The solution for my problem is to force EF to include the FlightPlan when retrieving an Airplane.

Answer Source

This is most likely due to lazy loading since your FlightPlan is virtual.

var airplane = db.Airplanes.First(); //pull airplane from db
var passengerAmount = airplane.FlightPlan.AmountOfPassengers //attempting to use 
// FlightPlan property after pulling Airplane from db should load the FlightPlan

You can also force EF to include the FlightPlan property when pulling from the db.

using System.Data.Entity;
var airplane = db.Airplanes.Include(m => m.FlightPlan).First();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download