1

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?

Mutudu
  • 11
  • 4
  • You might be able to define `B`, `B1`, `B2` as a type hierarchy. Each with a `[NotMapped]` property that returns a `C`, `C1`, `C2` record respectively. – Jeremy Lakeman Apr 22 '21 at 03:02
  • @JeremyLakeman Thanks your comment,but this will destroy the design of the domain model,it means technical implementation in turn affects the design of the business model. – Mutudu Apr 22 '21 at 03:18
  • I don't think you can set up an FK between B and C without a key. But it might be possible for B to own a C, with a discriminator? `new EntityTypeBuilder(p.OwnsOne(g => g.C).OwnedEntityType).HasDiscriminator ... `. But I don't know anything about EF Core support for records. – Jeremy Lakeman Apr 22 '21 at 05:15
  • @JeremyLakeman Hi Jeremy,I learned from the issue that owned does not support inheritance(https://github.com/dotnet/efcore/issues/9630),and will not necessarily support it in the foreseeable future(https://github.com/dotnet/efcore/issues/23870),so I am referring to your original suggestion.In addition, record is a new syntactic sugar,it is just a special class, efcore still uses the original logic to process it.Thanks again for your help. – Mutudu Apr 22 '21 at 06:26

0 Answers0