实现实体框架一对一的关系

时间:2016-11-18 13:42:55

标签: c# entity-framework code-first one-to-one ef-migrations

我正在尝试使用Code First实现Entity Framework中的一对一关系。我想创建一个有FlightPlan的飞机表。

飞机:

public class Airplane
{
    [Key]
    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
{
    [Key]
    [ForeignKey("Airplane")]
    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; }
}

当我使用Migrations初始化这些类时,会创建以下表结构:

enter image description here

在我设法创建一架装有FlightPlan的飞机后,无论我尝试什么,飞机都没有飞行计划。

enter image description here

enter image description here

我该如何解决这个问题?

修改

出于测试目的,我为每个更新的飞机添加了FlightPlan。修复此问题后,将创建一个用于添加Flightplan的路线。代码是:

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

我的问题的解决方案是在检索飞机时强制EF包含FlightPlan。

2 个答案:

答案 0 :(得分:0)

这很可能是由于您的FlightPlanvirtual而导致延迟加载。

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

从数据库中提取时,您还可以强制EF包含FlightPlan属性。

using System.Data.Entity;
var airplane = db.Airplanes.Include(m => m.FlightPlan).First();

答案 1 :(得分:0)

应该按以下方式完成:

public class Airplane
{
    [Key]
    public int Id { get; private set; }

    public virtual FlightPlan FlightPlan { get; private set; }

    // ... other properties
}

public class FlightPlan
{
    [Key]
    public int Id { get; private set; }

    public virtual Airplane Airplane { get; private set; }

    // ... other properties
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     modelBuilder.Entity<FlightPlan>()
       .HasRequired(flightPlan => flightPlan.Airplane)
       .WithOptional(airplane => airplane.FlightPlan);

       base.OnModelCreating(modelBuilder);
}

您的二传手当然可以是public