2

I'm not sure if this was possible in EF 6 or earlier. (Current version I use is EF Core 3.1.4) What I'm trying to achieve is to have a base entitiy with some properties and a connection to another entity. From the base entity to have 2 other entities with different connections (foreign keys or navigation properties) to other entities. Is this possible in any way or should I abandon the idea?

The error I get is:

A key cannot be configured on 'DerivedResource1' because it is a derived type. The key must be configured on the root type 'Resource'. If you did not intend for 'Resource' to be included in the model, ensure that it is not included in a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation property on a type that is included in the model.

And the code:

public class Resource : BaseEntity
{
    public string Name { get; set; }
    public string Description { get; set; }
    public ICollection<Connection1> Connection1 { get; set; }
}

   public class DerivedResource1 : Resource
{
    public int NrOfSeats { get; set; }
    public int Capacity { get; set; }
    public Guid Connection2Id { get; set; }
    public Connection2 Connection2 { get; set; }
}

    public class DerivedResource2 : Resource
{
    public string Title { get; set; }
    public string Text { get; set; }
    public ICollection<ManyToManyResource> ManyToManyResources { get; set; }
}

And the configurations looks like this:

 private void ConfigureResource(EntityTypeBuilder<Resource> config)
    {
        config.ToTable("Resources")
            .HasDiscriminator<int>("ResourceType")
            .HasValue<DerivedResource1>(1)
            .HasValue<DerivedResource2>(2);
    }

    private void ConfigureDerivedResource1(EntityTypeBuilder<DerivedResource1> config)
    {
        config.HasOne(x => x.Connection2)
            .WithMany(x => x.DerivedResource1)
            .HasForeignKey(x => x.Connection2Id);
    }

protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.Entity<Connection1>(config => ConfigureEntity(config, ConfigureConnection1));
        builder.Entity<DerivedResource1>(config => ConfigureEntity(config, ConfigureDerivedResource1));
        builder.Entity<Connection2>();
        builder.Entity<DerivedResource2>();
        builder.Entity<Resource>(config => ConfigureEntity(config, ConfigureResource));
        builder.Entity<ManyToMany>();
        builder.Entity<ManyToManyResource>(config => ConfigureEntity(config, ConfigureManyToManyResource));
    }
Iosif Bujor
  • 89
  • 2
  • 9

0 Answers0