2020-11-27 22:52:52 -05:00
|
|
|
|
using System;
|
2021-03-22 12:09:25 -04:00
|
|
|
|
using Data.Abstractions;
|
|
|
|
|
using Data.Context;
|
|
|
|
|
using Data.MigrationContext;
|
2020-11-27 22:52:52 -05:00
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
2020-11-29 17:01:52 -05:00
|
|
|
|
using SharedLibraryCore.Configuration;
|
2020-04-25 20:01:26 -04:00
|
|
|
|
|
|
|
|
|
namespace IW4MAdmin.Application.Factories
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// implementation of the IDatabaseContextFactory interface
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class DatabaseContextFactory : IDatabaseContextFactory
|
|
|
|
|
{
|
2020-11-29 17:01:52 -05:00
|
|
|
|
private readonly DbContextOptions _contextOptions;
|
|
|
|
|
private readonly string _activeProvider;
|
|
|
|
|
|
|
|
|
|
public DatabaseContextFactory(ApplicationConfiguration appConfig, DbContextOptions contextOptions)
|
2020-11-27 22:52:52 -05:00
|
|
|
|
{
|
2020-11-29 17:01:52 -05:00
|
|
|
|
_contextOptions = contextOptions;
|
|
|
|
|
_activeProvider = appConfig.DatabaseProvider?.ToLower();
|
2020-11-27 22:52:52 -05:00
|
|
|
|
}
|
2020-11-29 17:01:52 -05:00
|
|
|
|
|
2020-04-25 20:01:26 -04:00
|
|
|
|
/// <summary>
|
|
|
|
|
/// creates a new database context
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="enableTracking">indicates if entity tracking should be enabled</param>
|
|
|
|
|
/// <returns></returns>
|
|
|
|
|
public DatabaseContext CreateContext(bool? enableTracking = true)
|
|
|
|
|
{
|
2020-11-29 17:01:52 -05:00
|
|
|
|
var context = BuildContext();
|
2020-11-27 22:52:52 -05:00
|
|
|
|
|
|
|
|
|
enableTracking ??= true;
|
2020-11-29 17:01:52 -05:00
|
|
|
|
|
2020-11-27 22:52:52 -05:00
|
|
|
|
if (enableTracking.Value)
|
|
|
|
|
{
|
|
|
|
|
context.ChangeTracker.AutoDetectChangesEnabled = true;
|
|
|
|
|
context.ChangeTracker.LazyLoadingEnabled = true;
|
|
|
|
|
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.TrackAll;
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
context.ChangeTracker.AutoDetectChangesEnabled = false;
|
|
|
|
|
context.ChangeTracker.LazyLoadingEnabled = false;
|
|
|
|
|
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return context;
|
2020-04-25 20:01:26 -04:00
|
|
|
|
}
|
2020-11-29 17:01:52 -05:00
|
|
|
|
|
|
|
|
|
private DatabaseContext BuildContext()
|
|
|
|
|
{
|
|
|
|
|
return _activeProvider switch
|
|
|
|
|
{
|
|
|
|
|
"sqlite" => new SqliteDatabaseContext(_contextOptions),
|
|
|
|
|
"mysql" => new MySqlDatabaseContext(_contextOptions),
|
|
|
|
|
"postgresql" => new PostgresqlDatabaseContext(_contextOptions),
|
|
|
|
|
_ => throw new ArgumentException($"No context found for {_activeProvider}")
|
|
|
|
|
};
|
|
|
|
|
}
|
2020-04-25 20:01:26 -04:00
|
|
|
|
}
|
2020-11-29 17:01:52 -05:00
|
|
|
|
}
|