[英]Entity Framework Poor COUNT Performance
We are experiencing very poor performance using Entity Framework 5.0 with MySql Connector 6.6.6.0 for count based queries. 使用带有MySql Connector 6.6.6.0的Entity Framework 5.0进行基于计数的查询时,我们遇到的性能非常差。 Our data structure looks like:
我们的数据结构如下:
Table: Post =========== ID INT PRIMARY KEY MemberID INT NOT NULL SiteID INT NOT NULL Description VARCHAR(255) NOT NULL Image VARCHAR(255) NOT NULL CreatedDate DATETIME NULL
And using entity framework with a linq query like the following: 并使用具有linq查询的实体框架,如下所示:
var count = entities.Post.Where(p => p.SiteID == 1 && p.CreatedDate != null).Count();
We get the following generated SQL: 我们得到以下生成的SQL:
SELECT `Extent1`.`ID`, `Extent1`.`MemberID`, `Extent1`.`SiteID`, `Extent1`.`Description`, `Extent1`.`Image`, `Extent1`.`CreatedDate` FROM `Post` AS `Extent1` WHERE (`Extent1`.`SiteID` = 1) AND (`Extent1`.`CreatedDate` IS NOT NULL)
This reads all records and counts them in memory... Hugely inefficient as it should look something like: 这会读取所有记录并将其计入内存中......效率极低,因为它应该类似于:
SELECT COUNT(ID) FROM `Post` WHERE `SiteID` = 1 AND `CreatedDate` IS NOT NULL;
Is there anyway to hint to entity that we dont want to read all records into memory and just perform an SQL COUNT? 反正有没有提示我们不想将所有记录读入内存并只执行SQL COUNT?
Try 尝试
var count = entities.Post.Where(p =>
p.SiteID == 1 && p.CreatedDate != null).Query().Count();
http://msdn.microsoft.com/en-us/data/jj574232.aspx http://msdn.microsoft.com/en-us/data/jj574232.aspx
Has this at the bottom of the page: 在页面底部有这个:
Using Query to count related entities without loading them 使用Query来计算相关实体而不加载它们
Sometimes it is useful to know how many entities are related to another entity in the database without actually incurring the cost of loading all those entities. 有时,知道有多少实体与数据库中的另一个实体相关而实际上不会产生加载所有这些实体的成本是有用的。 The Query method with the LINQ Count method can be used to do this.
使用LINQ Count方法的Query方法可用于执行此操作。 For example:
例如:
using (var context = new BloggingContext())
{
var blog = context.Blogs.Find(1);
// Count how many posts the blog has
var postCount = context.Entry(blog)
.Collection(b => b.Posts)
.Query()
.Count();
}
Testing with EF 6 使用EF 6进行测试
db.Users.Count(u => u.LastName == "xyz")
and 和
db.Users.Where(u=>u.LastName=="xyz").Count()
produce identical sql queries. 生成相同的SQL查询。
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
COUNT(1) AS [A1]
FROM [dbo].[Users] AS [Extent1]
WHERE N'xyz' = [Extent1].[LastName]
) AS [GroupBy1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.