【发布时间】:2017-08-31 09:33:21
【问题描述】:
我们有一个包含 770 个表的大型数据库,并希望使用 EF 6.1x 进行一些性能测试。
我们只想查询这 770 个表中的 5 个。是否可以创建一个只有 5-6 个实体/DBSet 的“轻量级”DBContext 而不是使用完整的 770 个表上下文?
当我们使用完整上下文时,一个包含 4 个连接的简单查询需要 45 秒。那44秒太长了。 我们使用的是代码优先(逆向工程)。
问题: 当我们创建完整上下文的这样一个“轻量级”版本(即仅 5 个表)时,EF 抱怨与这 5 个表有某种关联的所有其他实体都缺少键。我们只映射这 5 个表的键、属性和关系,而不映射其余表。
由于用 LINQ 编写的查询只查询 5 个表,EF 应该简单地忽略其他 765 个表,但它不会。 为什么不呢? LazyLoading=true/false 似乎与此无关。
注意:显然,可以在数据库中创建一个视图,该视图执行我们在代码中使用 LINQ 查询所做的事情。问题是它可以用上面的“轻” DbContext 来完成。
这里有上下文的“轻量级”版本:
public class ItemLookupContext : DbContext
{
static ItemLookupContext()
{
Database.SetInitializer<ItemLookupContext>( null );
}
public ItemLookupContext()
: base( "Name=ItemLookupContext" )
{
//Configuration.LazyLoadingEnabled = true;
}
public DbSet<Identity> Identities { get; set; }
public DbSet<Item> Items { get; set; }
public DbSet<Price> Prices { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Brand> Brands { get; set; }
protected override void OnModelCreating( DbModelBuilder modelBuilder )
{
modelBuilder.Configurations.Add( new IdentityMap() );
modelBuilder.Configurations.Add( new ItemMap() );
modelBuilder.Configurations.Add( new PriceMap() );
modelBuilder.Configurations.Add( new DepartmentMap() );
modelBuilder.Configurations.Add( new BrandMap() );
//ignore certain entitities to speed up loading?
//does not work
modelBuilder.Ignore<...>();
modelBuilder.Ignore<...>();
modelBuilder.Ignore<...>();
modelBuilder.Ignore<...>();
modelBuilder.Ignore<...>();
}
}
【问题讨论】:
-
这当然是可能的并且实际上是推荐的。在较大的数据库环境中,为表的子集提供多个不同的上下文通常会提高性能。
-
一些代码将有助于理解您的问题,但我猜您会寻找类似stackoverflow.com/questions/17246069/… 的东西?
-
是 exe 的第一个简单查询,即触发上下文构建的一个查询?
-
@DavidG:问题是当我创建一个包含所有表子集的上下文时,为什么 EF 会抱怨甚至不在该上下文中的实体?
-
@Dave 我最终使用了强大的 EntityFramework Reverse POCO Code First Generator 来生成类。希望这会有所帮助。
标签: c# .net sql-server entity-framework dbcontext