我们有一个包含 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 似乎与此无关。
注意:很明显,可以在数据库中创建一个 View 来执行我们在代码中使用 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<...>();
}
}
最佳答案
您尝试使用“限界上下文”之类的 DDD 模式之一
因此,您可以查看 Julie Lerman 的这篇文章,Shrink EF Models with DDD Bounded Contexts
关于c# - Entity Framework 6 DBContext 只有所有表的一个子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25620248/