Does EF Core support an abstract base entity which is generic?

c# ef-code-first ef-fluent-api entity-framework entity-framework-core

Question

I remember there were problems with generic entities in previous EF. How about EF Core? I can't find docs related to this matter.

For example:

public abstract class Parent<TEntity> {
  public int EntityId { get; set; }
  public TEntity Entity { get; set; }
}

public class Child : Parent<Foo> {
}

public class OtherChild : Parent<Bar> {
}


// config for child entities includes this:
config.HasKey(c => c.EntityId);

Though this throws stating that child entities do not define a primary key, when they clearly do!

I can fix this by making Parent non-generic.

Are there official docs for this? Am I doing something wrong, or is this the expected behavior?

1
3
1/8/2017 7:46:43 AM

Accepted Answer

I can use this model in ef-core 1.1.0:

public abstract class Parent<TEntity>
{
    public int EntityId { get; set; }
    public TEntity Entity { get; set; }
}

public class Child : Parent<Foo>
{
}

public class OtherChild : Parent<Bar>
{
}

public class Foo
{
    public int Id { get; set; }
}

public class Bar
{
    public int Id { get; set; }
}

With this mapping in the context:

protected override void OnModelCreating(ModelBuilder mb)
{
    mb.Entity<Child>().HasKey(a => a.EntityId);
    mb.Entity<Child>().HasOne(c => c.Entity).WithMany().HasForeignKey("ParentId");
    mb.Entity<OtherChild>().HasKey(a => a.EntityId);
    mb.Entity<OtherChild>().HasOne(c => c.Entity).WithMany().HasForeignKey("ParentId");
}

Which leads to this fantastic model:

enter image description here

1
1/11/2017 10:02:42 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow