How to configure value object with inheritance relationship in EF Core 5 Fluent API

1.2k Views Asked by At

I have a DDD project with an aggregate A,it has an entity list property List<B>,and there is a value object C in entity B,the codes like this:

public class A
{
    public Guid Id {get; protected set;}
    public List<B> Bs {get; protected set;}
}

public class B
{
    public Guid Id {get; protected set;}
    public C C {get; protected set;}
}

public record C{}
public record C1:C{}
PUBLIC record C2:C{}

Cause the type C has sub class,in Fluent API I have configurated it like this:

public AClassTypeConfiguration : IEntityTypeConfiguration<A>
{
    public void Configure(EntityTypeBuilder<A> builder)
    {
        builder.HasKey(p => p.Id);
        builder.OwnsMany(p => p.Bs, p =>
        {
            p.HasKey(g => g.Id);
            p.Property(g => g.Id).ValueGeneratedNever();
            p.HasOne(g => g.C);
        });
    }
}

public CClassTypeConfiguration : IEntityTypeConfiguration<C>
{
    public void Configure(EntityTypeBuilder<C> builder)
    {
        builder.HasNoKey();
        builder.HasDiscriminator<int>("SubType")
            .HasValue<C1>(1);
            .HasValue<C2>(2);
    }
}

But when I debug the code it throw an InvalidOperationException with message "Unable to determine the relationship represented by navigation 'B.C' of type 'C'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'."

So how to configure value object with inheritance relationship in EF Core 5 Fluent API?

0

There are 0 best solutions below