C
C#4w ago
SWEETPONY

✅ How to get data from entity without includes?

I have this:
var shiftTask = await dbContext.Shifts
.Include(x => x.Resource)
.Include(x => x.Function)
.Include(x => x.CancelledByUser)
.Include(x => x.FinishedByUser)
.Include(x => x.CurrentLocation)
.Include(x => x.DefaultLocation)
.AsNoTracking()
.AsSplitQuery()
.FirstOrDefaultAsync(wt => wt.Identity == identity, context.RequestAborted)
.ConfigureAwait(false);
var shiftTask = await dbContext.Shifts
.Include(x => x.Resource)
.Include(x => x.Function)
.Include(x => x.CancelledByUser)
.Include(x => x.FinishedByUser)
.Include(x => x.CurrentLocation)
.Include(x => x.DefaultLocation)
.AsNoTracking()
.AsSplitQuery()
.FirstOrDefaultAsync(wt => wt.Identity == identity, context.RequestAborted)
.ConfigureAwait(false);
Is it possible to achive the same but without using a lot of includes?
6 Replies
leowest
leowest4w ago
you can with projection but it might ended up in a longer code, if u make some mapping extension it might be shorter and it might also be better to write some DTOs at this point specially if u dont need every single column from your tables and included tables like you're doing right now for better performance.
var shiftTask = await dbContext.Shifts
.Select(s => new ShiftDto
{
Id = s.Id,
Resources = s.Resource.Select(sr => new ShiftResourceDto
{
Id = sr.Id,
Name = sr.Name,
}).ToList()
})
// etc
.AsNoTracking()
.AsSplitQuery()
.FirstOrDefaultAsync(wt => wt.Identity == identity, context.RequestAborted)
.ConfigureAwait(false);
var shiftTask = await dbContext.Shifts
.Select(s => new ShiftDto
{
Id = s.Id,
Resources = s.Resource.Select(sr => new ShiftResourceDto
{
Id = sr.Id,
Name = sr.Name,
}).ToList()
})
// etc
.AsNoTracking()
.AsSplitQuery()
.FirstOrDefaultAsync(wt => wt.Identity == identity, context.RequestAborted)
.ConfigureAwait(false);
SWEETPONY
SWEETPONYOP4w ago
thanks for helping by the way, if we talk about perfomance how good is it compared to join tables? join i mean include
leowest
leowest4w ago
well the way you have right now, imagine if you have a table with 200 columns that references another table with 500 columns you will be retrieving all those 700 columns per item however if u only need say shift id, name, resource type you only retrieving 3 columns so yeah the impact can be huge as for number benchmark every case is a case
SWEETPONY
SWEETPONYOP4w ago
hm, understood thanks for helping me I will use dto instead of includes
MODiX
MODiX4w ago
If you have no further questions, please use /close to mark the forum thread as answered

Did you find this page helpful?