What is the most efficient way to obtain a property from an Entity?

Asked

Viewed 44 times

2

I’m using the EF6 and would like to know how to get the best performance when redeeming a unique property from a Entity.

Assuming the following case:

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

User class.Cs

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 is: is this the best way? Why am I picking up all users (large objects) and then just picking up a single property.

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

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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.