Entity Framework - Performance in count

后端 未结 5 752
清歌不尽
清歌不尽 2021-01-11 10:49

I\'ve a little question about performance with Entity Framework.

Something like

using (MyContext context = new MyContext())
{
    Document DocObject         


        
相关标签:
5条回答
  • 2021-01-11 11:26

    Yes, ToList() will evaluate the results (retrieving the objects from database), if you do not use ToList(), the objects aren´t retrieved from the database.

    Linq-To-Entities uses LazyLoading per default.

    It works something like this; When you query your underlying DB connection using Linq-To-Entities you will get a proxy object back on which you can perform a number of operations (count being one). This means that you do not get all the data from the DB at once but rather the objects are retrieved from the DB at the time of evaluation. One way of evaluating the object is by using ToList().

    Maybe you should read this.

    0 讨论(0)
  • 2021-01-11 11:28

    Your first query isnt fully transalted to sql - when you call .ToList().Count(), you are basically saying "download all, materialize it to POCO and call extension method named Count()" which, of course, take some time.

    Your second query is, however, transalted to something like select count(*) from Documents where GroupId = @DocObjectGroup which is much faster to execute and you arent materializing anything, just simple scalar.

    0 讨论(0)
  • 2021-01-11 11:30

    Calling ToList() then Count() will:

    • execute the whole SELECT FROM WHERE against your database
    • then materialize all the resulting entities as .Net objects
    • create a new List<T> object containing all the results
    • return the result of the Count property of the .Net list you just created

    Calling Count() against an IQueryable will:

    • execute SELECT COUNT FROM WHERE against your database
    • return an Int32 with the number of rows

    Obviously, if you're only interested in the number of items (not the items themselves), then you shouldn't ever call ToList() first, as it will require a lot of resources for nothing.

    0 讨论(0)
  • 2021-01-11 11:30

    Using the extension method Enumerable.ToList() will construct a new List object from the IEnumerable<T> source collection which means that there is an associated cost with doing ToList().

    0 讨论(0)
  • 2021-01-11 11:39

    Because ToList() will query the database for the whole objects (will do a SELECT * so to say), and then you'll use Count() on the list in memory with all the records, whereas if you use Count() on the IQueryable (and not on the List), EF will translate it to a simple SELECT COUNT(*) SQL query

    0 讨论(0)
提交回复
热议问题