Add new extension methods for retrieving data

This commit is contained in:
Noi 2022-03-19 18:10:10 -07:00
parent f52d8c81c8
commit 0a81f208ea
3 changed files with 31 additions and 0 deletions

19
Data/Extensions.cs Normal file
View file

@ -0,0 +1,19 @@
namespace BirthdayBot.Data;
internal static class Extensions {
/// <summary>
/// Gets the corresponding <see cref="GuildConfig"/> for this guild, or a new one if one does not exist.
/// If it doesn't exist in the database, <see cref="GuildConfig.IsNew"/> returns true.
/// </summary>
public static GuildConfig GetConfigOrNew(this SocketGuild guild, BotDatabaseContext db)
=> db.GuildConfigurations.Where(g => g.GuildId == (long)guild.Id).FirstOrDefault()
?? new GuildConfig() { IsNew = true, GuildId = (long)guild.Id };
/// <summary>
/// Gets the corresponding <see cref="UserEntry"/> for this user in this guild, or a new one if one does not exist.
/// If it doesn't exist in the database, <see cref="UserEntry.IsNew"/> returns true.
/// </summary>
public static UserEntry GetUserEntryOrNew(this SocketGuildUser user, BotDatabaseContext db)
=> db.UserEntries.Where(u => u.GuildId == (long)user.Guild.Id && u.UserId == (long)user.Id).FirstOrDefault()
?? new UserEntry() { IsNew = true, GuildId = (long)user.Guild.Id, UserId = (long)user.Id };
}

View file

@ -36,4 +36,10 @@ public class GuildConfig {
public ICollection<BlocklistEntry> BlockedUsers { get; set; }
[InverseProperty(nameof(UserEntry.Guild))]
public ICollection<UserEntry> UserEntries { get; set; }
/// <summary>
/// Gets if this instance is new and does not (yet) exist in the database.
/// </summary>
[NotMapped]
public bool IsNew { get; set; }
}

View file

@ -23,4 +23,10 @@ public class UserEntry {
[ForeignKey(nameof(GuildConfig.GuildId))]
[InverseProperty(nameof(GuildConfig.UserEntries))]
public GuildConfig Guild { get; set; } = null!;
/// <summary>
/// Gets if this instance is new and does not (yet) exist in the database.
/// </summary>
[NotMapped]
public bool IsNew { get; set; }
}