繁体   English   中英

EF Core 父子关系

[英]EF Core Parent Child Relation

我有一个Product类,它可能有插件,也可能是父产品的插件。

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Product> Parents { get; set; }
    public List<ProductAddon> ParentProducts { get; set; }
    public ICollection<Product> Addons { get; set; }
    public List<ProductAddon> AddonProducts { get; set; }
}

表示连接表的类。

public class ProductAddon
{
    public int Id { get; set; }
    public Product { get; set; }
    public Addon { get; set; }
    public DateTime Created { get; set; }
}

我如何在 OnModelCreating 中设置它才能工作?

 entity.HasOne(d => d.ProductAddon)
                    .WithMany(p => p.Product)
                    .HasForeignKey(d => d.ProductId)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("ConstaintNameFromSQL");

您需要在两个表之间设置外键,在这种情况下我使用一对多,因为我假设 1 个插件可以放在许多产品上? 但这只是一个基本假设。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM