我记得先前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
非通用。
这是否有正式文件?我做错了什么,或者这是预期的行为?
答案 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");
}
这导致了这个梦幻般的模型: