Skip to content

Instantly share code, notes, and snippets.

@svenrog
Created January 31, 2022 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svenrog/de4a5ced924f73af866a6279f94552f7 to your computer and use it in GitHub Desktop.
Save svenrog/de4a5ced924f73af866a6279f94552f7 to your computer and use it in GitHub Desktop.
Internal implementation of AspNetIdentitySchemaUpdater.
using EPiServer.Cms.UI.AspNetIdentity;
using EPiServer.Data;
using EPiServer.Data.Providers;
using EPiServer.Data.SchemaUpdates;
using EPiServer.Shell.Security;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
namespace YourProject.Infrastructure.Security
{
public class AspNetIdentitySchemaUpdater<TUser> : ISchemaUpdater where TUser : IdentityUser, IUIUser, new()
{
private readonly ApplicationOptions _options;
private readonly IDatabaseExecutorFactory _databaseExecutorFactory;
private readonly ApplicationDbContext<TUser> _applicationDbContext;
public AspNetIdentitySchemaUpdater(ApplicationOptions applicationOptions, IDatabaseExecutorFactory databaseExecutorFactory, ApplicationDbContext<TUser> applicationDbContext)
{
_options = applicationOptions;
_databaseExecutorFactory = databaseExecutorFactory;
_applicationDbContext = applicationDbContext;
}
public SchemaStatus GetStatus(IEnumerable<ConnectionStringOptions> connectionStringOptions)
{
var executor = _databaseExecutorFactory.CreateHandler(_options.ConnectionStringOptions);
if (!executor.Execute(() =>
{
using DbCommand dbCommand = executor.CreateCommand();
dbCommand.CommandType = CommandType.Text;
dbCommand.CommandText = "IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'AspNetUsers') SELECT 1 ELSE SELECT 0";
return (int)dbCommand.ExecuteScalar() == 1;
}))
{
return new SchemaStatus
{
ApplicationRequiredVersion = new Version(1, 0, 0),
DatabaseVersion = new Version(0, 0, 0),
ConnectionStringOption = _options.ConnectionStringOptions
};
}
return new SchemaStatus
{
ApplicationRequiredVersion = new Version(1, 0, 0),
DatabaseVersion = new Version(1, 0, 0),
ConnectionStringOption = _options.ConnectionStringOptions
};
}
public void Update(ConnectionStringOptions connectionStringOptions)
{
if (!_options.DisableAutoCreateSchema)
{
_applicationDbContext.GetService<IRelationalDatabaseCreator>().CreateTables();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment