【问题标题】:Calling 'Read' when the data reader is closed is not a valid operation in Entity Framework关闭数据读取器时调用“读取”不是实体框架中的有效操作
【发布时间】:2016-10-28 05:17:36
【问题描述】:

我在 Windows 应用程序 C# 中使用实体框架,尝试使用 DbContext 从两个实体中检索数据并希望进行简单的连接,但我的代码出现故障(在 var modellst 行)。我的示例代码如下

        using (var ctx = new DbEntities())
        {

            var lst = ctx.AUMaterials.Where(o => o.ServiceRequestTypeId == serviceReqId && o.SSStock.Quantity > 0).ToList();
            var modellst = ctx.AUModelMaterials.Where(o => o.ModelId == modelId).ToList();

            // here i want to make join on these two list
        }

这里首先列出 AUMaterials 实体中的数千条记录。而且我认为加载需要很长时间。同样的方式在 AUModelMaterials 实体中,这里也有数千条记录。但相同的代码在早期阶段运行良好。

【问题讨论】:

  • 你有导航属性还是集合属性?
  • 这里AUMaterials、AUModelMaterials、SSStock是相互关联的。AUMaterials与AUModelMaterials是一对多的关系,而AUMaterials与SSStock是一对一的关系。
  • 我的实体 'AUMaterial' 具有公共虚拟 ICollection AUModelMaterials { get;放; }

标签: c# .net entity-framework linq dbcontext


【解决方案1】:
 var results = (from t1 in context.AUMaterials
                      join t2 in context.AUModelMaterials
                      on  t1.Col1 equals t2.Col1
                      where t1.ServiceRequestTypeId == serviceReqId && t1.SSStock.Quantity > 0 && t2.ModelId == modelId
                      select new { t1, t2}).ToList();  

Joining 在多个列上

 var results = (from t1 in context.AUMaterials
                      join t2 in context.AUModelMaterials
                      on new {t1.Col1, t1.Col2, t1.Col3 } equals
                          new { t2.Col1, t2.Col2, t2.Col3 }
                      where t1.ServiceRequestTypeId == serviceReqId && t1.SSStock.Quantity > 0 && t2.ModelId == modelId
                      select new { t1, t2}).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多