I have a base class Foo, with all properties that I need across my application. The ui uses a derived class (FooUi) with the necessary ui properties. The database uses a derived class (FooEntity) with an Id property, for example. But that seems to be the crux of the matter, because according to the exception, this is probably not allowed in EF core. Is there an elegant solution here so that I don't have to pack the Id property in my base class, as I don't need it anywhere else and still got the possibility to have a key?
public class Foo
{
}
public class FooEntity : Foo
{
public int Id { get; set; }
}
public class FooDbContext : DbContext
{
public DbSet<FooEntity> Foos { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<FooEntity>(builder =>
{
builder.ToTable("Foos");
// here the exception occurs
builder.HasIndex(entity => entity.Id);
});
base.OnModelCreating(modelBuilder);
}
}
Exception
A key cannot be configured on 'FooEntity' because it is a derived type. The key must be configured on the root type 'Foo'. If you did not intend for 'Foo' 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.