c# - Entity Framework 6 DBContext 只有所有表的一个子集

标签 c# .net sql-server entity-framework dbcontext

我们有一个包含 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/

相关文章:

c# - HandleProcessCorruptedStateExceptions 不适用于 StackOverflow 异常

c# - 循环递归自连接表

c# - 检查组合框值是否为空

c# - 如何在不使用过时的 OracleConnection 类的情况下建立 OracleConnection

sql-server - 针对 IN () 子句 COLLATE DATABASE_DEFAULT

sql - SQL Server 数据库排序

sql-server - SQL 函数中的两个 return 语句是什么意思?

c# - setter 中的图像集成

C# 线性代数库

c# - 在 C# 中同步线程