I need to fetch an entity randomly as showed below, but ElementAtAsync does not exist. What is the reason for this and what can be a workaround?
var index = random.Next(maxValue:count);
var song = await Context.Songs.ElementAt(index);
I need to fetch an entity randomly as showed below, but ElementAtAsync does not exist. What is the reason for this and what can be a workaround?
var index = random.Next(maxValue:count);
var song = await Context.Songs.ElementAt(index);
If you only need one element from the db, and you already have the count, you can do something like this:
var index = random.Next(maxValue:count);
var songQuery = await Context.Songs
.OrderyBy(x => x.Something)
.Skip(index)
.Take(1)
.ToListAsync();
var song = songQuery.SingleOrDefault(); // this works due to the Take(1) above
I am not sure why it is not exist but a workaround can be like below.
var song await = Context.Songs.OrderBy(o => o.Id)
.Skip(index)
.FirstOrDefaultAsync();
This Linq query will cause same result but underlying query can be bit of different.