`from..where` or `FirstOrDefault` in LINQ

前端 未结 3 1570
滥情空心
滥情空心 2021-01-30 20:36

Traditionally, when I\'ve tried to get data for a user from a database, and I\'ve used the following method (to some degree):

DbUsers curUser = context.DbUsers.F         


        
相关标签:
3条回答
  • 2021-01-30 21:02

    If you need not whole entity, but some values from it, then use new {name = s.u_Name, email = s.u_Email}. Because, this object is much "lighter" for cunstruction. When you get entity with FirstOrDefault, it' saved in DBContext, but you don't do anything with it. So, i advice you to get only data you need.

    0 讨论(0)
  • 2021-01-30 21:09

    If you want to get only two fields, then you should project your entity before query gets executed (and in this case query gets executed when you call FirstOrDefault). Use Select operator for projection to anonymous object with required fields:

    var user = context.DbUsers
                      .Where(u => u.u_LoginName == id)
                      .Select(u => new { u.u_Name, u.u_Email })
                      .FirstOrDefault(); // query is executed here
    
    string name = user.u_Name; // user is anonymous object
    string email = user.u_Email;
    

    That will generate SQL like:

     SELECT TOP 1 u_Name, u_Email FROM DbUsers
     WHERE u_LoginName = @id
    

    In second case you are doing projection before query gets executed (i.e. enumeration started). That's why only required fields are loaded. But query will be slightly different (without TOP 1). Actually if you will convert second approach to lambda syntax, it will be almost same:

    var query = context.DbUsers
                       .Where(u => u.u_LoginName == id)
                       .Select(u => new { u.u_Name, u.u_Email }); 
    
    // query is defined but not executed yet
    foreach (var user in query) // executed now
    {
       //Stuff Here
    }
    

    And just to show complete picture, without projection you get all fields of first found user:

    DbUsers user = context.DbUsers
                          .Where(u => u.u_LoginName == id)
                          .FirstOrDefault(); // query is executed here
    
    string name = user.u_Name; // user is DbUsers entity with all fields mapped
    string email = user.u_Email;    
    

    In that case user entity is not projected before query is executed and you'll get all fields of user loaded from database and mapped to user entity:

     SELECT TOP 1 u_LoginName, u_Name, u_Email /* etc */ FROM DbUsers
     WHERE u_LoginName = @id
    
    0 讨论(0)
  • 2021-01-30 21:10

    The second is better. You only get the needed data from database so the network traffic is lighter.

    You can have the same result with extension methods:

    var user = context.DbUsers
                      .Where(x => x.u_LoginName == id)
                      .Select(x => new {...})
                      .FirstOrDefault();
    
    0 讨论(0)
提交回复
热议问题