1

I want to retrieve only one column of my data base. The following code works truly:

This is my customer in mysql-table/model-in-EF6

 public partial class customers
    {
        public customers()
        public int CustomerID { get; set; }
        public string FullName { get; set; }
        public string Mobile { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
        public string Image { get; set; }
    }
public List<customers> GetAllCustomers()
        {
            return myContext.customers.ToList();
        }

This is my question:

var GetOneColumn = myContext.CustomerRepository.GetAllCustomers().Select(f=>f.FullName);

Does it retrieve all columns from customers in database and then select only one column (FullName) from retrieved data or not, it retrieve just only one column(FullName) from data base? If it retrieve all data from data base what is the correct code (Linq)?

How could I find that??

Dharman
  • 30,962
  • 25
  • 85
  • 135
ehsan_kabiri_33
  • 341
  • 6
  • 13

1 Answers1

2

Since you're using a .ToList() EF will

  1. Retrieve all customers from database
  2. Map them to customer objects
  3. Later, when you compute GetOneColumn, you do a projection on them (iterating through already materialized object list)

To retrieve only one column,

  1. Remove the .ToList() from the repository, and return a IQueryable<Customers>
  2. Call a .ToList() after your select var GetOneColumn = myContext.CustomerRepository.GetAllCustomers().Select(f=>f.FullName).ToList();

So, your code would be

public IQueryable<customers> GetAllCustomers()
{
      return myContext.customers;
}
// later in code
var GetOneColumn = myContext.CustomerRepository.GetAllCustomers().Select(f=>f.FullName).ToList();

See what's going on for yourself! Break up your code into steps and debug:

var allCustomers = myContext.CustomerRepository.GetAllCustomers();
var allCustomerNames = allCustomers.Select(f=>f.FullName);

Alternatively, run a profiler on your DB, or enable logging of queries in EF

To see all the queries that EF is generating you can do something like this

using (var context = new BlogContext())
{
    context.Database.Log = Console.Write;

    // Your code here...
}

See more details in the docs and Log Queries executed by Entity Framework DbContext

If you read this far, then it's worth knowing what will actually cause EF to send a query - see How Queries Work

Basically, this happens whenever you start enumerating through the elements of an IQueryable<T> (including LINQ methods like First(), Last(), Single(), ToList(), ToArray(), and the like)

ironstone13
  • 3,325
  • 18
  • 24