Improve migration Script

This commit is contained in:
runebaas 2018-05-13 14:14:50 +02:00
parent 32ae82ca8d
commit 3fa4115502
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
4 changed files with 52 additions and 14 deletions

View file

@ -14,7 +14,9 @@ namespace Geekbot.net.Database
public DbSet<RollsModel> Rolls { get; set; }
public DbSet<MessagesModel> Messages { get; set; }
public DbSet<SlapsModel> Slaps { get; set; }
// public DbSet<UserSettingsModel> UserSettings { get; set; }
// public DbSet<RoleSelfServiceModel> RoleSelfService { get; set; }
public DbSet<GlobalsModel> Globals { get; set; }
// public DbSet<UserSettingsModel> UserSettings { get; set; }
// public DbSet<RoleSelfServiceModel> RoleSelfService { get; set; }
}
}

View file

@ -0,0 +1,18 @@
using System.ComponentModel.DataAnnotations;
namespace Geekbot.net.Database.Models
{
public class GlobalsModel
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Value { get; set; }
public string Meta { get; set; }
}
}

View file

@ -8,6 +8,7 @@ using Geekbot.net.Commands.Utils.Quote;
using Geekbot.net.Database.Models;
using Geekbot.net.Lib.Extensions;
using Geekbot.net.Lib.Logger;
using MtgApiManager.Lib.Model;
using Newtonsoft.Json;
using StackExchange.Redis;
@ -172,8 +173,6 @@ namespace Geekbot.net.Database
{
try
{
// drop the guild qounter
if(q.Name.ToString() != "0") continue;
var user = new MessagesModel()
{
GuildId = guild.Id.AsLong(),
@ -242,16 +241,18 @@ namespace Geekbot.net.Database
{
try
{
_database.Users.Add(new UserModel()
{
UserId = user.Id.AsLong(),
Username = user.Username,
Discriminator = user.Discriminator,
AvatarUrl = user.GetAvatarUrl(ImageFormat.Auto, 1024),
IsBot = user.IsBot,
Joined = user.CreatedAt,
UsedNames = new [] {user.Username}
});
var namesSerialized = _redis.HashGet($"User:{user.Id}", "UsedNames").ToString();
var names = Utf8Json.JsonSerializer.Deserialize<string[]>(namesSerialized);
_database.Users.AddIfNotExists(new UserModel()
{
UserId = user.Id.AsLong(),
Username = user.Username,
Discriminator = user.Discriminator,
AvatarUrl = user.GetAvatarUrl(ImageFormat.Auto, 1024),
IsBot = user.IsBot,
Joined = user.CreatedAt,
UsedNames = names
}, model => model.UserId.Equals(user.Id.AsLong()));
_database.SaveChanges();
}
catch

View file

@ -0,0 +1,17 @@
using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace Geekbot.net.Lib.Extensions
{
public static class DbSetExtensions
{
public static EntityEntry<T> AddIfNotExists<T>(this DbSet<T> dbSet, T entity, Expression<Func<T, bool>> predicate = null) where T : class, new()
{
var exists = predicate != null ? dbSet.Any(predicate) : dbSet.Any();
return !exists ? dbSet.Add(entity) : null;
}
}
}