简体   繁体   中英

EF Core Parent Child Relation

I have a class Product which may have Addons and also be an Addon of Parent Products.

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

The class that represents the join table.

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

How do I setup this in OnModelCreating to be working?

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

You need to have a Foreign key setup between the two tables, in this case I used a one to many, as I assume 1 addon can be placed on many products? But this is just a base assumption.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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