实体框架Fluent API中的两个FK

时间:2018-03-02 14:40:35

标签: c# .net entity-framework entity-framework-6 ef-fluent-api

我正在努力连接两个非常简单的表:

[Table("Item")]
public class Item
{
    [Key]
    [Column("itemId", TypeName = "int")]
    public int ItemId { get; set; }
}

[Table("LinkedItems")]
public class LinkedItem
{
    [Key]
    [Column("itemId", TypeName = "int")]
    public int ItemId { get; set; }

    [Column("parentItemId", TypeName = "int")]
    public int ParentItemId { get; set; }
}

LinkedItem表格中有两个外键:

  1. itemId,指向表格Item以展示自己

  2. parentItemId,指向表Item以显示其父级

  3. 我想做到这样的事情:

    [Table("Item")]
    public class Item
    {
        [Key]
        [Column("itemId", TypeName = "int")]
        public int ItemId { get; set; }
    
        public ICollection<LinkedItem> ChildItems { get; set; }
        public LinkedItem LinkedItem { get; set; }
    }
    
    [Table("LinkedItems")]
    public class LinkedItem
    {
        [Key]
        [Column("itemId", TypeName = "int")]
        public int ItemId { get; set; }
    
        [Column("parentItemId", TypeName = "int")]
        public int ParentItemId { get; set; }
    
        public Item Item { get; set; }
        public Item ParentItem { get; set; }
    }
    

    我成功创建了从Item到LinkedItem的连接:

    modelBuilder.Entity<Item>().HasOptional(i => i.LinkedItem).WithRequired(i => i.Item);
    

    但我无法添加其他连接。你能帮我解决这两个表的Fluent API配置吗?

1 个答案:

答案 0 :(得分:3)

此类不需要LinkedItem类。你可以用一个类完成这个任务。

public class Item
{
    public int Id { get; set; }

    public int ParentItemId { get; set; }

    public virtual Item ParentItem { get; set; }

    public virtual ICollection<Item> ChildItems { get; set; }
}

        modelBuilder.Entity<Item>()
            .HasRequired(entity => entity.ParentItem)
            .WithMany(entity => entity.ChildItems)
            .HasForeignKey(entity => entity.ParentItemId);

否则只需添加:

modelBuilder.Entity<Item>()
    .HasMany(entity => entity.ChildItems)
    .WithRequired(entity => entity.ParentItem)
    .HasForeignKey(entity => entity.ParentItemId);

编辑:延长答案。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Item>()
        .HasOptional(entity => entity.LinkedItem)
        .WithRequired(entity => entity.Item);

    modelBuilder.Entity<Item>()
        .HasMany(entity => entity.ChildItems)
        .WithRequired(entity => entity.ParentItem)
        .HasForeignKey(entity => entity.ParentItemId);
}

[Table("Item")]
public class Item
{
    [Key]
    public int ItemId { get; set; }

    public virtual ICollection<LinkedItem> ChildItems { get; set; }

    public virtual LinkedItem LinkedItem { get; set; }
}

[Table("LinkedItem")]
public class LinkedItem
{
    [Key]
    public int ItemId { get; set; }

    public int ParentItemId { get; set; }

    public virtual Item Item { get; set; }

    public virtual Item ParentItem { get; set; }
}

这让我得到了我设置的测试表的结果: enter image description here