我記得先前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
非泛型來解決這個問題。
有官方文件嗎?我做錯了什麼,或者這是預期的行為?
我可以在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");
}
這導致了這個夢幻般的模型: