本文介绍了实体框架4.1代码第一:获取具有特定基类的所有实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DbContext,设置不同的 DbSet< T> ,所有类型都派生于同一个基类:

I have a DbContext with set up different DbSet<T>s with all types that derive from the same base class:

public class Foo : Entity { }
public class Bar : Entity { }

MyDbContext : DbContext
{
  public DbSet<Foo> Foos { get; set; }
  public DbSet<Bar> Bars { get; set; }
}

是否可以获取所有具有实体一个查询中的基类,如:

Is it possible to get all entities which have the Entitybase class in one query, like:

DbContext.Set<Entity>();  // doesn't work

我试图引入一个显式的 DbSet< Entity> ; 到DbContext,但这会导致数据库中所有实体的一个大表。

I tried to introduce an explicit DbSet<Entity> to the DbContext, but that results in one big table for all entities in the database.

其他问题:如果这样工作,关于查询接口?

Additional question: If this works somehow, what about querying for interfaces?

编辑:

我按照Ladislav的说明Mrnka的,我的映射如下:

I followed the instructions on Ladislav Mrnka's link and did my mappings like follows:

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数据注释,验证该属性是否尚未从模型中明确排除。确保它是一个有效的原始属性。

我还试图将密钥显式设置为 Id property:

I also tried to set the Key explicitly to the Id property:

modelBuilder.Entity<Foo>().Map(x => {...})
  .HasKey(x => x.Id)
  .HasMany(x => x.Tags).WithMany();

我缺少什么?

推荐答案

您需要引入。之后, DbContext.Set< Entity>()将工作,您仍然会有每个实体的表。

You need to introduce TPC inheritance. After that DbContext.Set<Entity>() will work and you will still have table per entity.

这篇关于实体框架4.1代码第一:获取具有特定基类的所有实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 15:55