在Entity Framework中创建一个多个自引用类

时间:2017-02-14 13:28:42

标签: c# entity-framework ef-code-first

如何让EF以正确的方式从下面的课程中构建数据库?有没有办法只使用DataAnnotation-Attributes存档它?

public class Item
{
    [Key]
    public long ItemId { get; set; }
    ...
    public virtual ICollection<Item> PrevItems { get; set; }
    public virtual ICollection<Item> NextItems { get; set; }
}

1 个答案:

答案 0 :(得分:0)

以下是我的解决方案:

  1. 创建配置类:

    public ItemConfiguration()
    {
        this.HasMany(x => x.NextItems)
           .WithMany(x => x.PrevItems)
           .Map(x => x.ToTable("RelatedItems"));
    }
    
  2. 在DbContext中覆盖OnModelCreating

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new ItemConfiguration());
    }
    
  3. 我不确定这是否100%正确,但似乎有效。

    如果有人知道如何使用DataAnnotation-Attributes存档,我很乐意知道!