Optimize the !quote database query

This commit is contained in:
runebaas 2020-09-23 16:28:50 +02:00
parent ae9b9caeb9
commit 58bd4d17d0
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6

View file

@ -33,23 +33,23 @@ namespace Geekbot.Bot.Commands.Utils.Quote
} }
[Command] [Command]
[Summary("Return a random quoute from the database")] [Summary("Return a random quote from the database")]
public async Task GetRandomQuote() public async Task GetRandomQuote()
{ {
try try
{ {
var s = _database.Quotes.Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong())).ToList(); var totalQuotes = await _database.Quotes.CountAsync(e => e.GuildId.Equals(Context.Guild.Id.AsLong()));
if (!s.Any()) if (totalQuotes == 0)
{ {
await ReplyAsync(Localization.Quote.NoQuotesFound); await ReplyAsync(Localization.Quote.NoQuotesFound);
return; return;
} }
var random = _randomNumberGenerator.Next(0, s.Count - 1); var random = _randomNumberGenerator.Next(0, totalQuotes - 1);
var quote = s[random]; var quote = _database.Quotes.Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong())).Skip(random).Take(1);
var embed = QuoteBuilder(quote); var embed = QuoteBuilder(quote.FirstOrDefault());
await ReplyAsync("", false, embed.Build()); await ReplyAsync("", false, embed.Build());
} }
catch (Exception e) catch (Exception e)