实体框架6 DBContext只包含所有表的子集

Joh*_*ohn 6 .net c# sql-server entity-framework dbcontext

我们有一个包含770个表的庞大数据库,并希望使用EF 6.1x进行一些性能测试.

我们只想查询这770个表中的5个.是否可以创建一个只有5-6个实体/ DBSets的"轻"DBContext,而不是使用完整的770-tables-context?

当我们使用完整上下文时,一个包含4个连接的简单查询需要45秒.那是44秒太长了.我们正在使用代码优先(逆向工程).

问题: 当我们创建完整上下文的这种"轻型"版本(即仅5个表)时,EF抱怨所有与这5个表有某种关联的所有其他实体都缺少密钥.我们只映射这5个表的键,属性,关系,而不是其余的.

由于用LINQ编写的查询只查询5个表,因此EF应该忽略其他765个表,但它不会. 为什么不?LazyLoading = true/false似乎与此无关.

注意:显然,可以在DB中创建一个视图,该视图使用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<...>();
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

你尝试过像"Bounded Context"这样的东西,这是DDD模式之一

因此,您可以查看Julie Lerman撰写的文章,使用DDD有界上下文缩小EF模型