"unable to determine the principal end of an association" 对于两个一对多关系

"unable to determine the principal end of an association" for two one to many relationships

我有以下实体:DevicePrinter

public class Device
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DeviceId { get; set; }

    public int? DefaultPrinterId { get; set; }
    [ForeignKey("DefaultPrinterId")]
    public virtual Printer DefaultPrinter { get; set; }
}

public class Printer
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PrinterId { get; set; }

    public int? DeviceId { get; set; }
    [ForeignKey("DeviceId")]
    public virtual Device Device { get; set; }
}

设备和打印机之间有 2 个关系

当我使用 Entity Framework 生成数据库时,出现错误: "unable to determine the principal end of an association" 不难找到有关此错误如何与一对一关系相关的信息,但我还没有发现任何关于这与两个一对多关系的关系。

有什么方法可以告诉 EF 我不是要定义一对一关系?

问题是您没有指定关系的 "end"。因为两者的关系不是 1-1,而是 1-n。

一个Device可以有一个DefaultPrinter,也就是说Printer可以是很多设备的"Default Printer"

使用 Fluent API 可以轻松解决(删除现有的 [ForeignKey] 属性)。像这样:

modelBuilder.Entity<Printer>()
    .HasOptional(i => i.Device)
    .WithMany() //we don't have navigation property on the other side
    .HasForeignKey(i => i.DeviceId);

modelBuilder.Entity<Device>()
    .HasOptional(i => i.DefaultPrinter)
    .WithMany() //we don't have navigation property on the other side
    .HasForeignKey(i => i.DefaultPrinterId);

假设您想知道哪些设备具有特定的打印机 "default printer"。

public class Device
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int DeviceId { get; set; }

    public int? DefaultPrinterId { get; set; }

    public virtual Printer DefaultPrinter { get; set; }

    //that's new
    public virtual ICollection<Printer> PrintersThatLoveMe { get; set; }
}

public class Printer
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int PrinterId { get; set; }

    public int? DeviceId { get; set; }

    public virtual Device Device { get; set; }

    //that's new
    public virtual ICollection<Device> DevicesThatLoveMe { get; set; }

}

映射:

modelBuilder.Entity<Printer>()
    .HasOptional(i => i.Device)
    .WithMany(i => i.PrintesThatLoveMe)
    .HasForeignKey(i => i.DeviceId);

modelBuilder.Entity<Device>()
    .HasOptional(i => i.DefaultPrinter)
    .WithMany(i => i.DevicesThatLoveMe)
    .HasForeignKey(i => i.DefaultPrinterId);

希望对您有所帮助!