EF ...两个字段的多余重复值

时间:2018-08-12 10:34:52

标签: c# entity-framework

我有两个实体来保存产品和产品的相关产品...存在一对多关系...在存储信息之前一切都正确,但是在数据库中存储了两个重复的字段 相关产品ID 产品ID

public class RelatedCatalogs : EntityBase
{
    public Guid ProductID { get; set; }
    public Guid RelatedProducID { get; set; }

    public Product RelatedProductCatalog { get; set; }


    public int Priority { get; set; }
}

产品类别:

public class Product{
    public Guid ProductID { get; set; }

    public string Name { get; set; }

    [ForeignKey("RelatedProductID")]
    public virtual List<RelatedCatalogs> RelatedCatalogs { get; set; }

。 。 。 }

现在要解决此问题需要做什么?

1 个答案:

答案 0 :(得分:0)

您的问题似乎类似于this,请尝试:

public class Product
{
    public Guid ProductID { get; set; }
    public string Name { get; set; }
    ...
    [InverseProperty("Product")]
    public virtual List<RelatedCatalogs> RelatedCatalogs { get; set; }
}

public class RelatedCatalogs : EntityBase
{
    public Guid ID { get; set; }

    [ForeignKey("Product")]
    public Guid ProductID { get; set; }
    public Product Product { get; set; }

    [ForeignKey("RelatedProductCatalog")]
    public Guid RelatedProductID { get; set; }
    public Product RelatedProductCatalog { get; set; }

    public int Priority { get; set; }
}

然后,您可以添加提到的流利代码以避免循环:

modelBuilder.Entity<RelatedCatalogs>()
    .HasRequired(r => r.RelatedProductCatalog)
    .WithMany()
    .HasForeignKey(r => r.RelatedProductID)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<RelatedCatalogs>()
    .HasRequired(r => r.Product)
    .WithMany(p => p.RelatedCatalogs)
    .HasForeignKey(r => r.ProductID);