Best way for retrieving single record results in LINQ to SQL

后端 未结 6 1320
清酒与你
清酒与你 2021-02-01 13:09

If I query a table with a condition on the key field as in:

        var user = from u in dc.Users
                   where u.UserName == usn
                   s         


        
相关标签:
6条回答
  • 2021-02-01 13:53

    Also it should be noted that First/FirstOrDefault/Single/SingleOrDefault are the point of execution for a LINQ to Sql command. Since the LINQ statement has not been executed before that, it is able to affect the SQL generated (e.g., It can add a TOP 1 to the sql command)

    0 讨论(0)
  • 2021-02-01 13:53

    I would use the SingleOrDefault method.

    var user = (from u in dc.Users
                       where u.UserName == usn
                       select u).SingleOrDefault();
    
    0 讨论(0)
  • 2021-02-01 13:57

    Try something like this:

    var user = (from u in dc.Users
                       where u.UserName == usn
                       select u).FirstOrDefault();
    

    The FirstOrDefault method returns the first element of a sequence that satisfies a specified condition or a default value if no such element is found.

    0 讨论(0)
  • 2021-02-01 13:59

    Why not something like

    var user = dc.Users.SingleOrDefault(u=> u.UserName==usn);
    
    0 讨论(0)
  • 2021-02-01 14:01

    Another option is to use Contains(username) as opposed to "=="

    var user = (from u in dc.UserInfo 
                          where u.Users.Contains(username) 
                          select u).SingleOrDefault();
    
    0 讨论(0)
  • 2021-02-01 14:09

    I would use First() or FirstOrDefault().

    The difference: on First() there will be an exception thrown if no row can be found.

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