【发布时间】:2018-06-10 01:41:31
【问题描述】:
我正在使用 EF Core。我在数据库表 Articles 中有大约 2500 条记录。
在使用 EF 编译 SQL 的管理工作室中,我得到了一些 MS 的结果。在程序中大约 30 秒。 .Select() 是问题所在。不知道怎么优化了。
1:之前
List<Article> articles = await db.Articles.Select(x => new Article { Title = x.Title, Description = x.Description, Body = x.Body, Authors = x.Authors, PhotoAuthors = x.PhotoAuthors, Tags = x.Tags }).ToListAsync();
2:现在
List<Article> articles = await db.Articles.FromSql("SELECT [x].[Title], [x].[Description], [x].[Body], [x].[Authors], [x].[PhotoAuthors], [x].[Tags] FROM[Articles] AS[x]").Select(x => new Article { Title = x.Title, Description = x.Description, Body = x.Body, Authors = x.Authors, PhotoAuthors = x.PhotoAuthors, Tags = x.Tags }).ToListAsync();
结果还是一样的:/
编辑:解决方案是不使用 .ToList()
使用:
IQueryable<Article> articles = db.Articles.Select(x => new Article { Title = x.Title, Description = x.Description, Body = x.Body, Authors = x.Authors, PhotoAuthors = x.PhotoAuthors, Tags = x.Tags }).AsNoTracking();
IQueryable 丢失函数,例如我稍后使用的 .Split 或 Intersects。
【问题讨论】:
-
我在 EF 6(非 Ef Core)性能方面遇到了很多困难,我注意到问题在于 SQL 结果映射到类。我正在研究一个遗留系统,无法解决建模错误以改善性能问题... =/ 现在我使用 Dapper,性能方面的一切都好得多。
-
为什么需要选择 -
db.Articles不是返回IQueryable<Article>? -
好吧,我正在尝试选择必要的列。没有选择它也很慢..因为创建 2500 个对象
-
您要寻找的最终结果是什么
articles(或多少)?例如之后你会过滤你的文章吗? -
是的,然后我过滤文章。我需要使用 Split 函数来查看是否有任何关键字与单词匹配
标签: c# entity-framework linq select entity-framework-core