【发布时间】:2011-04-28 13:04:34
【问题描述】:
我有一个 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; }
}
是否可以在一个查询中获取所有具有Entitybase 类的实体,例如:
DbContext.Set<Entity>(); // doesn't work
我尝试向 DbContext 引入显式 DbSet<Entity>,但这会导致数据库中的所有实体都使用一个大表。
附加问题:如果这能以某种方式工作,那么查询接口呢?
编辑:
我按照 Ladislav Mrnka 的link 上的说明进行了如下映射:
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();
我错过了什么?
【问题讨论】:
-
感谢您的链接。但似乎这是使用数据库优先方法的答案,而我正在寻找使用代码优先方法的解决方案。也许我在这里遗漏了什么,但我没有找到任何提示我的问题。
标签: inheritance mapping ef-code-first entity-framework-4.1 base-class