You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iot/projects/Infrastructure/Configuration/EFConfigurationProvider.cs

59 lines
1.9 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Primitives;
namespace Infrastructure.Configuration
{
public class EFConfigurationProvider : ConfigurationProvider
{
private readonly List<EFConfigurationValue> _configValues;
private readonly DbContextOptionsBuilder<EFConfigurationContext> _builder;
public EFConfigurationProvider(Action<DbContextOptionsBuilder> optionsAction, List<EFConfigurationValue> configValues)
{
this._configValues = configValues;
this._builder = new DbContextOptionsBuilder<EFConfigurationContext>();
optionsAction(_builder);
ChangeToken.OnChange(
() => this.GetReloadToken(),
() =>
{
this.Load(true);
this.OnReload();
});
}
public override void Load()
{
this.Load();
}
private void Load(bool reload = false)
{
using (var dbContext = GetDbContext())
{
if (!reload)
{
dbContext.Database.EnsureCreated();
}
Data = (dbContext.Values.Any() ? dbContext.Values.ToList() : CreateAndSaveDefaultValues(dbContext)).ToDictionary(o => o.Id, o => o.Value);
}
}
private EFConfigurationContext GetDbContext()
{
var dbContext = new EFConfigurationContext(_builder.Options);
return dbContext;
}
private List<EFConfigurationValue> CreateAndSaveDefaultValues(EFConfigurationContext dbContext)
{
dbContext.Values.AddRange(_configValues.ToArray());
dbContext.SaveChanges();
return _configValues;
}
}
}