EF代码首先 - 一对一或零

时间:2017-07-04 15:35:10

标签: entity-framework ef-code-first ef-migrations

我有两个实体:

        modelBuilder.Entity<GPSdevice>()
            .HasOptional(e => e.Truck)
            .WithOptionalPrincipal()
            .WillCascadeOnDelete(false);

我想创建一对一或零的关系(每个GPS设备可以链接到任何卡车(但只能连接到一个卡车)或根本不连接(

我写下面的代码:

    public override void Up()
    {
        AddColumn("dbo.Truck", "GPSdevice_ID", c => c.Int());
        CreateIndex("dbo.Truck", "GPSdeviceID");
        CreateIndex("dbo.Truck", "GPSdevice_ID");
        AddForeignKey("dbo.Truck", "GPSdeviceID", "dbo.GPSdevices", "ID");
        AddForeignKey("dbo.Truck", "GPSdevice_ID", "dbo.GPSdevices", "ID");
    }

但它会创建以下迁移:

public int? GPSdeviceID { get; set; }

为什么它会再创建一个字段以及如何使用当前字段GPSdeviceID?

增加:

如果我删除

    modelBuilder.Entity<GPSdevice>()
        .HasOptional(e => e.Truck)
        .WithOptionalPrincipal(e=>e.GPSdevice).Map(p=>p.MapKey("GPSdeviceID"))
        .WillCascadeOnDelete(false);

并添加MapKey:

    public override void Up()
    {
        CreateIndex("dbo.Truck", "GPSdeviceID");
        AddForeignKey("dbo.Truck", "GPSdeviceID", "dbo.GPSdevices", "ID");
    }

结果我得到以下迁移代码:

{{1}}

然后我收到以下错误:

  

引用的表中没有主键或候选键   &#39; dbo.GPSdevices&#39;匹配外部引用列列表   key&#39; FK_dbo.Truck_dbo.GPSdevices_GPSdeviceID&#39;。无法创建   约束或索引。查看以前的错误。

1 个答案:

答案 0 :(得分:0)

使用此:

public partial class GPSdevice
{       
    public GPSdevice()
    {
    }

    public int ID { get; set; }

    public string UserName { get; set; }


    public virtual Truck Truck { get; set; }

}

public partial class Truck
{       
    public Truck()
    {
    }

    public int TruckID { get; set; }

    public string TruckNo { get; set; }

    public string Make { get; set; }

    public virtual GPSdevice GPSdevice { get; set; }
}   

modelBuilder.Entity<GPSdevice>()
            .HasOptional(o => o.Truck)
            .WithRequired(ad => ad.GPSdevice);

modelBuilder.Entity<Truck>()
    .HasKey(e => e.TruckID);