Answered Single does top(2)

  • Wednesday, May 20, 2009 7:28 PM
     
     
    Kind of intresting to see that when i do single, EF used top(2) in the sql query. Anyone know why?

    var

     

     

    customer = db.Customers.Single(c => c.CustomerID == "ALFKI");

    SELECT TOP (2)

    [Extent1].[Address] AS [Address],

    [Extent1].[City] AS [City],

    [Extent1].[CompanyName] AS [CompanyName],

    [Extent1].[ContactName] AS [ContactName],

    [Extent1].[ContactTitle] AS [ContactTitle],

    [Extent1].[Country] AS [Country],

    [Extent1].[CustomerID] AS [CustomerID],

    [Extent1].[Fax] AS [Fax],

    [Extent1].[Phone] AS [Phone],

    [Extent1].[PostalCode] AS [PostalCode],

    [Extent1].[Region] AS [Region]

    FROM [dbo].[Customers] AS [Extent1]

    WHERE N'ALFKI' = [Extent1].[CustomerID]

    Zeeshan Hirani

All Replies

  • Wednesday, May 20, 2009 9:35 PM
     
     Answered
    Hi zeeshan.
    It's the only way to throw an exception if there are more than one result.
    If you only want the first, use First instead of Single.
  • Thursday, May 21, 2009 7:45 AM
    Moderator
     
     Answered
    We need the first result and to know if there were more. I figured top 2 would be a little more efficient than streaming the whole set and aborting early which us what LINQ to SQL does :)

    [)amien