我有一个 DbContext 设置了不同DbSet<T>
的 s,所有类型都派生自同一个基类:
public class Foo : Entity { }
public class Bar : Entity { }
MyDbContext : DbContext
{
public DbSet<Foo> Foos { get; set; }
public DbSet<Bar> Bars { get; set; }
}
是否可以在一个查询中获取所有具有Entity
基类的实体,例如:
DbContext.Set<Entity>(); // doesn't work
我尝试向 DbContext 引入显式DbSet<Entity>
,但这会为数据库中的所有实体生成一个大表。
附加问题:如果这以某种方式起作用,那么查询接口呢?
编辑:
我按照 Ladislav Mrnka链接上的说明进行了如下映射:
MyDbContext : DbContext
{
public DbSet<Entity> Entities { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Foo
modelBuilder.Entity<Foo>().Map(x =>
{
x.MapInheritedProperties();
x.ToTable("Foo");
})
.HasMany(x => x.Tags).WithMany();
modelBuilder.Entity<Foo>()
.Property(x => x.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
// Bar
// same thing for Bar and a bunch of other Entities
base.OnModelCreating(modelBuilder);
}
}
现在抛出错误
属性“Id”不是“Foo”类型的声明属性。使用 Ignore 方法或 NotMappedAttribute 数据注释验证该属性是否已从模型中显式排除。确保它是有效的原始属性。
我还尝试将 Key 显式设置为Id
属性:
modelBuilder.Entity<Foo>().Map(x => {...})
.HasKey(x => x.Id)
.HasMany(x => x.Tags).WithMany();
我错过了什么?