Entity Framework Poor COUNT Performance

后端 未结 2 633
挽巷
挽巷 2021-01-06 05:45

We are experiencing very poor performance using Entity Framework 5.0 with MySql Connector 6.6.6.0 for count based queries. Our data structure looks like:

Table: P         


        
相关标签:
2条回答
  • 2021-01-06 06:23

    Testing with EF 6

    db.Users.Count(u => u.LastName == "xyz")
    

    and

    db.Users.Where(u=>u.LastName=="xyz").Count()
    

    produce identical sql queries.

    SELECT 
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT 
        COUNT(1) AS [A1]
        FROM [dbo].[Users] AS [Extent1]
        WHERE N'xyz' = [Extent1].[LastName]
    )  AS [GroupBy1]
    
    0 讨论(0)
  • 2021-01-06 06:38

    Try

    var count = entities.Post.Where(p => 
           p.SiteID == 1 && p.CreatedDate != null).Query().Count();
    

    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

    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. 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(); 
    }
    
    0 讨论(0)
提交回复
热议问题