简体   繁体   中英

Owned Entity with Polymorphism EF core 6

Bonjour

I need some help to understand how we map OwnedEntity when they are polymorph. I have this inventory hierarchy of records that are linked to a product class.

public abstract record Inventory
{
    protected Inventory() { }
}

public record NoProductInventory : Inventory
{
    public NoProductInventory()
    {
    }
}

public sealed record ProductLevelInventory : Inventory
{
    public int Stock { get; private set; } = default!;
    public int LowStock { get; private set; } = default!;
    protected ProductLevelInventory() {}
    public ProductLevelInventory(int stock, int lowStock) : base()
    {
        Stock = stock;
        LowStock = lowStock;
    }
}

public sealed record VariantLevelInventory : Inventory
{
    public int Stock { get; private set; } = default!;
    public int LowStock { get; private set; } = default!;
    public int SomeOption { get; private set; }
    protected VariantLevelInventory() {}
    public VariantLevelInventory(int stock, int lowStock) : base()
    {
        Stock = stock;
        LowStock = lowStock;
    }
}

The Product class Definition

public class Product
{
    ....
    public Inventory Inventory { get; private set; } = default!;
    ....
}

I am using fluent API in order to mapped those entities

public class ProductEntityTypeBuilder : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.OwnsOne(x => x.Inventory, bld =>
        {
            bld.ToTable("Inventories");
            // bld.Property(x => x.TrackInventory).IsRequired();
            bld.Property(x => x.Stock).IsRequired(false);
            bld.Property(x => x.LowStock).IsRequired(false);
            // bld.Property(x => x.InventoryTrackType).IsRequired(false);
        });
    }
}

My question is: how can I tell EF which Inventory record to use? I don't want to use casting to figure out what kind of inventory a product has.

Good Day !

Owned entities are meant to be used as value types, containing and encapsulate multiple values which belong together and don't have a meaning on their own, ie M.netaryAmount which consists of a Amount and a Currency property.

You can't do this right now. If you need hierarchies, you have to convert your owned types into entities and use it as regular navigation properties on the base type which are distinguished via a discriminator.

Owned types do not support inheritance Owned Types: Shortcommings

Current shortcomings

Owned entity types cannot have inheritance hierarchies

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