EF代码优先:关联表中具有其他字段的多对多自引用关系

时间:2018-08-01 12:24:36

标签: c# .net entity-framework

我们拥有产品的精髓。可以在本产品中插入其他本身就是产品的附加模块(也可以不插入)。另外,产品本身可以插入其他产品

public class Product : INotifyPropertyChanged
{
    public int ProductId { get; set; }

    /// <summary>
    /// In which modules can you insert
    /// </summary>
    public virtual ObservableCollection<Product> ForProducts { get; set; }


    /// <summary>
    ///  What modules can be inserted into me
    /// </summary>
    public virtual ObservableCollection<Product> AddModules {get; set;}

...还有其他属性

使用FluentApi,我们调整关系:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Product>().HasMany(x => x.AddModules).WithMany(y => y.ForProducts)
            .Map(x => x.ToTable("ProductToProduct"));
    }

一切都很棒,一切正常。但是您需要向链接表添加其他数据,例如:

// how many pieces of this product can be inserted into another product
public int Count {get; set;}

// unit of measure (pieces, sets, etc.)

public string Unit {get; set;}  ... and another properties

我想通过一个附加表来获得产品与我之间的多对多关系,您可以在其中添加附加列。

编辑:在推送的答案中,两个实体之间的多对多关系。我对如何做同样的事情感兴趣,只不过是将产品表与自身连接起来。

0 个答案:

没有答案
相关问题