With Entity Framework is it better to use .First() or .Take(1) for “TOP 1”?

前端 未结 5 1038
青春惊慌失措
青春惊慌失措 2021-01-01 08:55

We are implementing some EF data repositories, and we have some queries which would include TOP 1

I have read many posts suggesting to use .Ta

相关标签:
5条回答
  • 2021-01-01 09:14

    Redirect the DataContext Log property to Console.Out or a TextFile and see what query each option produces.

    0 讨论(0)
  • 2021-01-01 09:14

    First will query Take 1, so there is no difference in query. Calling FirstOrDefault will be one step statement, because Take returns IEnumerable do you will need to call First anyway.

    First will throw exception so FirstOrDefault is always preferred.

    And ofcourse people who wrote EF query converter are smart enough to call Take 1 instead executing entire result set and returning first item.

    You can this verify using SQL profiler.

    0 讨论(0)
  • 2021-01-01 09:20

    From LINQPad:

    C#:

    age_Centers.Select(c => c.Id).First();
    age_Centers.Select(c => c.Id).FirstOrDefault();
    age_Centers.Select(c => c.Id).Take(1).Dump();
    

    SQL:

    SELECT TOP (1) [t0].[Id]
    FROM [age_Centers] AS [t0]
    GO
    
    SELECT TOP (1) [t0].[Id]
    FROM [age_Centers] AS [t0]
    GO
    
    SELECT TOP (1) [t0].[Id]
    FROM [age_Centers] AS [t0]
    

    *Note that Take(1) enumerates and returns an IQueryable.

    0 讨论(0)
  • 2021-01-01 09:24
    **First()** operates on a collection of any number of objects and returns the first object.        **Take(1)** operates on a collection of any number of objects and returns a collection containing the first object.
    

    You can also use Single Single() operates on a collection of exactly one object and simply returns the object.

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

    How .First() works:

    If the collection is of type IList, then the first element is accessed by index position which is different depending on the collection implementation. Otherwise, an iterator returns the first element.

    And .Take(int count) always iterate.

    If there's any gain, it happens if the collection implements IList and the speed to access the first element by index is higher than that of returning an iterator. I don't believe it will be significant. ;)

    Sources:

    http://www.hookedonlinq.com/FirstOperator.ashx

    http://www.hookedonlinq.com/TakeOperator.ashx

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