C# 如何在同一实体上创建多对多关系?

C# 如何在同一实体上创建多对多关系?,c#,entity-framework,many-to-many,code-first,C#,Entity Framework,Many To Many,Code First,例如,我有Poduct实体: public class Product : DatabaseEntity { public int Id {get; set;} public int Name {get; set;} public decimal Price {get; set;} ... } 我想为产品创建类似产品的可编辑集合。因此,它类似于多对多,但在同一实体-产品上,因此我更新了我的模型,如下所示: public class Product : Data

例如,我有
Poduct
实体:

public class Product : DatabaseEntity
{
    public int Id {get; set;}
    public int Name {get; set;}
    public decimal Price {get; set;}

    ...
}
我想为产品创建类似产品的可编辑集合。因此,它类似于多对多,但在同一实体-产品上,因此我更新了我的模型,如下所示:

public class Product : DatabaseEntity
{
    public int Id {get; set;}
    public int Name {get; set;}
    public decimal Price {get; set;}

    public ICollection<Product> SimilarProducts { get; private set; }
    public void AddSimilar(Product product)
    {
       SimilarProducts.Add(product);
    }

    ...
}
已实施的编辑产品操作:

public ActionResult Edit(ProductEditModel productEditModel)
{

    if(!string.IsNullOrEmpty(productEditModel.SelectedSimilarProductLinkName))
    {
         var similarProduct = _productRepository.GetProduct(productEditModel.SelectedSimilarProductId);
         product.AddSimilar(similarProduct);
     }
    _productRepository.AddProduct(product);
}
作废IPProductRepository.AddProduct(产品产品)

public void AddProduct(Product product)
{
     _repository.InsertOrUpdate(product);
}

但我得到了奇怪的结果:在我的数据库中,向product添加了
product\u Id
字段,并且没有像通常的多对多实体实现那样存储相关产品Id的
ProductProduct
表或类似表。如何手动创建此表?我遗漏了什么或做错了什么?

谢谢你的建议,我已经找到了解决方案:

型号:

public class Product : DatabaseEntity
{
    public int Id {get; set;}
    public int Name {get; set;}
    public decimal Price {get; set;}

    public ICollection<Product> ParentSimilars { get; set; }
    public ICollection<Product> ChildSimilars { get; set; }

    [NotMapped]
    public IEnumerable<Product> SimilarProducts
    {
        get
        {
           return ChildSimilars.Concat(ParentSimilars);
        }
    }

    ...
}
公共类产品:数据库实体
{
公共int Id{get;set;}
公共int名称{get;set;}
公共十进制价格{get;set;}
公共ICollection parentsimilar{get;set;}
公共ICollection子类{get;set;}
[未映射]
公共可数相似积
{
得到
{
返回ChildSimilars.Concat(ParentSimilars);
}
}
...
}
数据库上下文设置

modelBuilder.Entity<Product>()
            .HasMany(p => p.ChildSimilars)
            .WithMany(p => p.ParentSimilars)
            .Map(m =>
                     {
                         m.MapLeftKey("Product_Id");
                         m.MapRightKey("SimilarProduct_Id");
                    });
modelBuilder.Entity()
.HasMany(p=>p.childsimilar)
.WithMany(p=>p.parentsimilar)
.Map(m=>
{
m、 MapLeftKey(“产品标识”);
m、 MapRightKey(“类似产品标识”);
});

基本上就是这些。

看看这里@sweel,谢谢你的建议。
modelBuilder.Entity<Product>()
            .HasMany(p => p.ChildSimilars)
            .WithMany(p => p.ParentSimilars)
            .Map(m =>
                     {
                         m.MapLeftKey("Product_Id");
                         m.MapRightKey("SimilarProduct_Id");
                    });