【问题标题】:Linq Join Data Table to Entity Framework - Not Evaluating resultsLinq 将数据表连接到实体框架 - 不评估结果
【发布时间】:2017-08-18 08:07:57
【问题描述】:

我在 Windows 10.1 和 SQL Sever 2016 中的 Visual Studio 15 下工作。我的系统通过将 CSV 文本文件导入数据表来处理它们,然后使用从数据表中获得的值更新 SQL 表。

我正在尝试如下使用 LINQ JOIN 语句:

            var books = from x in dt.AsEnumerable()
            join y in db.BookFiles.AsEnumerable()
            on
            new {printid = x.Field<string>("PrintID"), packageid = x.Field<string>("PackageID")}
            equals
            new {printid = y.PrintId, packageid = y.PackageID}
            select y; 

            foreach(var book in books) 
            {
              \\Do Something
            }

dt 是数据表,db 是 SQL 数据库的实体框架表示。我将 dt 限制为仅 3 条记录进行测试。

当 foreach 语句被求值时,它只会继续求值,直到内存不足。

以下解决方案有效,所以我认为这不是数据问题:

        List<BookFile> books = new List<BookFile>();
        foreach (DataRow dr in dt.Rows)
        {
            string printid = dr.Field<string>("PrintID");
            string packageid = dr.Field<string>("PackageID");


            var book = (from data in db.BookFiles 
            where data.PrintId == printid && data.PackageID == packageid 
            select data).Single();

            books.Add(book);
        }
        foreach(var book in books)
        {
          \\Do Something
        }

我是否错误地设置了 JOIN?我尝试先使用数据库,然后再使用连接中的数据表。我尝试为连接字段使用定义的类。任何信息都会有所帮助。

【问题讨论】:

  • AsEnumerable() call here db.BookFiles.AsEnumerable() 导致 BookFiles 表完全加载到内存中。对于这种情况,您最好使用第二种方法。

标签: c# sql entity-framework linq join


【解决方案1】:

删除 AsEnumerable()(它会将所有表加载到内存中,您不需要在加入之前使用它)并将 ToList()(在那一刻将对数据库进行真正的查询)添加到 foreach 中的书籍,如下所示

var books = from x in dt
                        join y in db.BookFiles
                        on
                        new { printid = x.Field<string>("PrintID"), packageid = x.Field<string>("PackageID") }
                        equals
                        new { printid = y.PrintId, packageid = y.PackageID }
                        select y;

            foreach (var book in books.ToList())
            {
              \\Do Something
            }

【讨论】:

  • 当我尝试在没有可枚举的 Visual Studio 的情况下使用 System.Data.Datable dt 时,将产生“找不到源类型 'DataTable' 的查询模式的实现。'Join' not found”如果我使用没有 .AsEnumerable 的 dt.AsEnumerable 和 db.Bookfiles,我会得到相同的结果。 dt 仅包含 3 行,因此它不应该是内存消耗。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多