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