What is the most efficient way to get an Entity property?

2

I'm using EF6 and would like to know how to get the best performance by redeeming a single property from a Entity .

Assuming the following case:

  

Let's say I need to fetch all names from a 5000-line user table.

User.cs class

public int ID {get; set;}

public string Name {get; set;}

um monte de coisa a mais...

So I set up this function:

public IEnumerable<string> GetAllNames()
{
   var list = new List<string>();
   var users = _context.Users.OrderBy(u => u.Name);
   foreach(var user in users)
   {
     list.Add(user.Name);
   }
   return list;
}

And it worked.

But the question remains: is this the best way? Why am I catching all users (large objects) and then just grabbing a single property.

If it is not the best way ... what is it?

    
asked by anonymous 20.12.2018 / 19:18

1 answer

4

I work with NHibernate, but I believe you can do something like this.

public IEnumerable<string> GetAllNames() => _context.Users.Select(u => u.Name).OrderBy(u => u);
    
20.12.2018 / 19:23