SCHALE.GameServer/SCHALE.Common/Database/ServicesExtesions.cs

46 lines
1.6 KiB
C#
Raw Normal View History

2024-04-18 07:12:10 +00:00
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
2024-04-18 07:12:10 +00:00
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
2024-04-18 07:12:10 +00:00
namespace SCHALE.Common.Database
{
public static class ServicesExtesions
{
public static void AddMongoDBProvider(this IServiceCollection services, string connectionString)
{
services.AddDbContext<SCHALEContext>(opt =>
{
opt.UseMongoDB(connectionString, "SCHALE");
});
}
}
public static class ValueConversionExtensions
{
public static PropertyBuilder<T> HasJsonConversion<T>(this PropertyBuilder<T> propertyBuilder) where T : class, new()
{
ValueConverter<T, string> converter = new ValueConverter<T, string>
(
v => JsonConvert.SerializeObject(v),
v => JsonConvert.DeserializeObject<T>(v) ?? new T()
);
ValueComparer<T> comparer = new ValueComparer<T>
(
(l, r) => JsonConvert.SerializeObject(l) == JsonConvert.SerializeObject(r),
v => v == null ? 0 : JsonConvert.SerializeObject(v).GetHashCode(),
v => JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(v))
);
propertyBuilder.HasConversion(converter);
propertyBuilder.Metadata.SetValueConverter(converter);
propertyBuilder.Metadata.SetValueComparer(comparer);
return propertyBuilder;
}
}
2024-04-18 07:12:10 +00:00
}