mardi 30 avril 2019

Get random entities (including children) using NewGuide() in .Net Core 2

I needed to get some random entities from database, using EF Core, including some children entities. First, I used this example :

var entities = await context.Entities
    .Include(p => p.Children1)
    .Include(p => p.Children2)
    .Include(p => p.Children3)
    .OrderBy(p => Guid.NewGuide())
    .Take(4)
    .ToListAsync();

The problem for this using is that Guid.NewGuide() return children randomly, and is not assigned only for main entities. So, sometimes I get Children1, sometimes not, and I need to apply this random interogation only for the main.

I find a solution, but I think is not the best, and need to know if exist another better. First time, I get the ids for some random main entities, then I get all there entities including children (this is bad because I do 2 request into database):

var ids = context.Entities
    .OrderBy(p => Guid.NewGuid())
    .Take(4)
    .ToListAsync();

var entities = context.Entities
    .Include(p => p.Children1)
    .Include(p => p.Children2)
    .Include(p => p.Children3)
    .Where(p => ids.Contains(p.Id)
    .ToListAsync();




Aucun commentaire:

Enregistrer un commentaire