dav*_*ser 7 mapping inheritance base-class ef-code-first entity-framework-4.1
我有一个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; }
}
Run Code Online (Sandbox Code Playgroud)
是否可以Entity
在一个查询中获取具有基类的所有实体,例如:
DbContext.Set<Entity>(); // doesn't work
Run Code Online (Sandbox Code Playgroud)
我试图向DbSet<Entity>
DbContext 引入一个显式,但这会为数据库中的所有实体生成一个大表.
附加问题:如果这种方式有效,那么查询接口呢?
编辑:
我按照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);
}
}
Run Code Online (Sandbox Code Playgroud)
这引发了错误
属性"Id"不是"Foo"类型的声明属性.使用Ignore方法或NotMappedAttribute数据批注验证是否未从模型中显式排除该属性.确保它是有效的原始属性.
我还尝试将Key明确设置为Id
属性:
modelBuilder.Entity<Foo>().Map(x => {...})
.HasKey(x => x.Id)
.HasMany(x => x.Tags).WithMany();
Run Code Online (Sandbox Code Playgroud)
我错过了什么?