EF Core是否支持通用的抽象基础实体?

时间:2017-01-08 07:46:43

标签: c# entity-framework ef-code-first entity-framework-core ef-fluent-api

我记得先前EF中的通用实体存在问题。 EF Core怎么样?我找不到与此事有关的文档。

例如:

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);

虽然这会引发说明子实体没有定义主键,但是当他们显然做的时候!

我可以通过使Parent非通用。

来解决此问题

这是否有正式文件?我做错了什么,或者这是预期的行为?

1 个答案:

答案 0 :(得分:1)

我可以在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; }
}

在上下文中使用此映射:

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");
}

这导致了这个梦幻般的模型:

enter image description here