More work on figuring out the DB stuff and converting EF code to linqtodb where it's easy

This commit is contained in:
Kwoth
2023-07-09 06:50:04 +00:00
parent be1d14d095
commit 842a8a2f71
17 changed files with 210 additions and 180 deletions

View File

@@ -0,0 +1,36 @@
#nullable disable
using Microsoft.EntityFrameworkCore;
using NadekoBot.Services.Database;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Db;
public static class PollExtensions
{
public static IEnumerable<Poll> GetAllPolls(this DbSet<Poll> polls)
=> polls.Include(x => x.Answers)
.Include(x => x.Votes)
.ToArray();
public static void RemovePoll(this DbContext ctx, int id)
{
var p = ctx.Set<Poll>().Include(x => x.Answers).Include(x => x.Votes).FirstOrDefault(x => x.Id == id);
if (p is null)
return;
if (p.Votes is not null)
{
ctx.RemoveRange(p.Votes);
p.Votes.Clear();
}
if (p.Answers is not null)
{
ctx.RemoveRange(p.Answers);
p.Answers.Clear();
}
ctx.Set<Poll>().Remove(p);
}
}

View File

@@ -52,7 +52,7 @@ public class PollRunner
finally { _locker.Release(); }
await using var uow = _db.GetDbContext();
var trackedPoll = uow.Poll.FirstOrDefault(x => x.Id == Poll.Id);
var trackedPoll = uow.Set<Poll>().FirstOrDefault(x => x.Id == Poll.Id);
trackedPoll.Votes.Add(voteObj);
uow.SaveChanges();
return true;

View File

@@ -24,15 +24,15 @@ public class PollService : IExecOnMessage
_eb = eb;
using var uow = db.GetDbContext();
ActivePolls = uow.Poll.GetAllPolls()
.ToDictionary(x => x.GuildId,
x =>
{
var pr = new PollRunner(db, x);
pr.OnVoted += Pr_OnVoted;
return pr;
})
.ToConcurrent();
ActivePolls = uow.Set<Poll>().GetAllPolls()
.ToDictionary(x => x.GuildId,
x =>
{
var pr = new PollRunner(db, x);
pr.OnVoted += Pr_OnVoted;
return pr;
})
.ToConcurrent();
}
public Poll CreatePoll(ulong guildId, ulong channelId, string input)
@@ -44,10 +44,10 @@ public class PollService : IExecOnMessage
return null;
var col = new IndexedCollection<PollAnswer>(data.Skip(1)
.Select(x => new PollAnswer
{
Text = x
}));
.Select(x => new PollAnswer
{
Text = x
}));
return new()
{
@@ -66,7 +66,7 @@ public class PollService : IExecOnMessage
{
using (var uow = _db.GetDbContext())
{
uow.Poll.Add(p);
uow.Set<Poll>().Add(p);
uow.SaveChanges();
}
@@ -98,8 +98,13 @@ public class PollService : IExecOnMessage
var toDelete = await msg.Channel.SendConfirmAsync(_eb,
_strs.GetText(strs.poll_voted(Format.Bold(usr.ToString())), usr.GuildId));
toDelete.DeleteAfter(5);
try { await msg.DeleteAsync(); }
catch { }
try
{
await msg.DeleteAsync();
}
catch
{
}
}
public async Task<bool> ExecOnMessageAsync(IGuild guild, IUserMessage msg)