【问题标题】:How to create many-to-many relationship on the same entity?如何在同一个实体上创建多对多关系?
【发布时间】:2013-06-04 22:01:38
【问题描述】:

例如我有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);
    }

    ...
}

我还更新了我的DbContext 课程:

modelBuilder.Entity<Product>()
                .HasMany(p => p.SimilarProducts)
                .WithOptional()
                .WillCascadeOnDelete(false);

实施了编辑产品操作:

public ActionResult Edit(ProductEditModel productEditModel)
{

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

void IProductRepository.AddProduct(Product product);

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

但是我得到了奇怪的结果:在我的数据库中添加了 Product_Id 字段,并且没有像 ProductProduct 表或类似存储相关产品 ID 的东西,就像通常的多对多实体实现一样。如何手动创建此表?我错过了什么或做错了什么?

【问题讨论】:

标签: c# entity-framework many-to-many code-first


【解决方案1】:

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

型号:

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);
        }
    }

    ...
}

DbContext 设置

modelBuilder.Entity<Product>()
            .HasMany(p => p.ChildSimilars)
            .WithMany(p => p.ParentSimilars)
            .Map(m =>
                     {
                         m.MapLeftKey("Product_Id");
                         m.MapRightKey("SimilarProduct_Id");
                    });

基本上就是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多