query result what should i use Count() or Any()

后端 未结 2 641
星月不相逢
星月不相逢 2021-01-27 07:37

I am checking login of a user by this repository method,

  public bool getLoginStatus(string emailId, string password)
    {
        var query = from r in taxidb         


        
相关标签:
2条回答
  • 2021-01-27 08:12

    The sql generated will be different between the two calls. You can check by setting your context.Log property to Console.Out or something.

    Here's what it will be:

    SELECT COUNT(*) AS [value]
    FROM [dbo].[Registrations] AS [t0]
    WHERE [t0].[EmailId] = @p0 and [t0].Password = @p1
    
    SELECT 
        (CASE 
            WHEN EXISTS(
                SELECT NULL AS [EMPTY]
                FROM [dbo].[Registrations] AS [t0]
                WHERE [t0].[EmailId] = @p0 and [t0].Password = @p1
                ) THEN 1
            ELSE 0
         END) AS [value]
    

    In this case, I doubt it will make any difference because EmailID is probably a unique index so there can only be 1 result. In another case where count can be > 1, Any would be preferable because the second query allows sql server to short circuit the search since it only needs to find one to prove that any exist.

    0 讨论(0)
  • 2021-01-27 08:32

    You could express it quite a bit shorter like this:

    return taxidb.Registrations.Any(r => r.EmailId == emailId && r.Password==password);
    
    0 讨论(0)
提交回复
热议问题