2024-04-18 07:12:10 +00:00
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
2024-04-26 15:50:30 +00:00
|
|
|
|
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;
|
2024-04-26 15:50:30 +00:00
|
|
|
|
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");
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-04-26 15:50:30 +00:00
|
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|