Question

I have some big entities with about 20 properties, and in some cases I need to create DropDownLists from that. In a SelectList you only end using 2 properties (ID and Name) from the original 20 returned by the query.

I'm using this method to load this:

new SelectList(db.Contacts.AsNoTracking().Where(x => x.idTenant == CurrentTenantID), "ContactId", "Name");

This is working fine, but the query on the Contacts dbset is obviously returning all the columns. How should I narrow the columns from 20 to 2 in order to have a lighter query to database?

I know I could do a Stored Procedure or View in database just for this cases, and use this for DropDownList population but... there is another way of doing it using directly the Entity Framework?

This happens in several entities, not just Contacts, so I would like to have a clear strategy for handling this scenaries.

Was it helpful?

Solution

You could add a .Select on to your query:

new SelectList(db.Contacts.AsNoTracking()
    .Where(x => x.idTenant == CurrentTenantID)
    .Select(x => new { x.ContactId, x.Name })
    , "ContactId", "Name");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top