Entity Framework - Performance in count

后端 未结 5 754
清歌不尽
清歌不尽 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: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 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.

提交回复
热议问题