Reputation: 4817
If I have this
var selectedEntities = db.MyEntities.Include(item => item.RelatedEntities);
It will load all properties (columns) in MyEntities but also all properties in ReleatedEntities. If I only need one property from RelatedEntities, how would I specify that?
Upvotes: 13
Views: 8089
Reputation: 96
use .Select() and anonymous type to restrict the columns you want
var result = await _appDbContext.Companies
.AsNoTracking()
.Select(company => new
{
Company = company,
EmployeeIds = company.Employees.Select(emp => emp.Id)
})
.ToListAsync()
.ConfigureAwait(false);
Upvotes: 6
Reputation: 845
I was looking for the same, and after referring to other questions it seems like it's not possible. The understanding i got is that an EF entity is represented by the collection of it's properties, and hence loading individual values will not fully define the Entity.
To load only selected properties, we need to use Select query, instead of loading the related data. The query will result in an anonymous type.
Note : If the resulting type contains any entity, then the changes will be tracked. Refer Tracking and projections
References :
Upvotes: 6