EF代码优先 - 使用可选元素添加反向属性

时间:2015-09-18 21:12:02

标签: entity-framework

我有以下课程

    public class Order  {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    [Required]
    public DateTime Date { get; set; }
    [Required]
    [MaxLength(100)]
    public string From { get; set; }

    public int? TreatGuestEntryID { get; set; }
    [ForeignKey("TreatGuestEntryID")]
    public TreatedGuestEntry TreatGuestEntry { get; set; }

...

public class TreatedGuestEntry  {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[MaxLength(200)]
public string Company { get; set; }
public string TypeOfTreat { get; set; }

这可以按预期工作 - 在我的Orders表中它创建了外键。

现在我想在TreatedGuestEntry中为订单添加一个反向属性。 我添加

时得到的最好(至少在某种程度上有效)
modelBuilder.Entity<TreatedGuestEntry>()
.HasOptional(a => a.Order)
.WithOptionalDependent(a => a.TreatGuestEntry)
.Map(a=>a.MapKey("TreatGuestEntryID"));

并进一步将TreatedGuestEntry的键重命名为TreatGuestEntryID。 但我在数据库中没有任何关系,并且表中的TreatGuestEntryID也不再是键(FK)。

我的方法用简单的话说: 在我的订单中,我想要一个可选的TreatedGuestEntry(我需要访问外键) - 并且在相关的TreatedGuestEntry中我想访问订单。

1 个答案:

答案 0 :(得分:1)

在您的情况下,FK TreatGuestEntryID不是PK,这意味着它是1:n的关系。因此,您必须在另一方放置Collection Order

public class Order
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    public DateTime Date { get; set; }

    [Required]
    [MaxLength(100)]
    public string From { get; set; }

    public int? TreatGuestEntryID { get; set; }

    public TreatedGuestEntry TreatGuestEntry { get; set; }
}

public class TreatedGuestEntry
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [MaxLength(200)]
    public string Company { get; set; }

    public string TypeOfTreat { get; set; }

    public ICollection<Order> Orders { get; set; }
}

映射:

modelBuilder.Entity<Order>()
    .HasOptional(i => i.TreatGuestEntry)
    .WithMany(i => i.Orders)
    .HasForeignKey(i => i.TreatGuestEntryID)
    .WillCascadeOnDelete(false);

生成的迁移:

CreateTable(
    "dbo.Orders",
    c => new
        {
            ID = c.Int(nullable: false, identity: true),
            Date = c.DateTime(nullable: false),
            From = c.String(nullable: false, maxLength: 100),
            TreatGuestEntryID = c.Int(),
        })
    .PrimaryKey(t => t.ID)
    .ForeignKey("dbo.TreatedGuestEntries", t => t.TreatGuestEntryID)
    .Index(t => t.TreatGuestEntryID);

CreateTable(
    "dbo.TreatedGuestEntries",
    c => new
        {
            ID = c.Int(nullable: false, identity: true),
            Company = c.String(maxLength: 200),
            TypeOfTreat = c.String(),
        })
    .PrimaryKey(t => t.ID);