我已经通过 TPC 策略创建了一个带有表的数据库(SQLite),因此一个抽象类和其他几个派生自它。在我的应用程序中,我将获取抽象类中实现的某个字段的所有元素(例如
Name
)。问题是,每个派生类在从 DbSet<>
派生的类中都有自己的 DbContext
字段,而且我还不知道如何在不采用某些特殊集合或将所有内容连接到一个 IEnumerable
中的情况下遍历所有项目。
实体:
public abstract class Animal
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Cat : Animal
{
public string EducationLevel { get; set; }
}
public class Dog : Animal
{
public string FavoriteToy { get; set; }
}
上下文:
public class MainDbContext : DbContext
{
public DbSet<Cat> Cats { get; set; }
public DbSet<Dog> Dogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Animal>().UseTpcMappingStrategy();
}
}
如何生成所有动物
Animal
,其中Name
可以是“鲍勃”?
查询必须始终从 an 开始 您可以使用 :
将类型添加为实体public DbSet<Animal> Animals { get; set; }
并在查询中使用它
var animals=context.Animals.Where(a=>a.Name=="Bob").ToList();
或使用 DbContext.Set 方法:
var animals=context.Set<Animal>().Where(a=>a.Name=="Bob").ToList();
如果您需要经常查询
Animals
,物业更方便