MigrateDatabaseToLatestVersion no running Seed() method - c#

I'm trying to automatically generate my database if it doesn't exists and run the Seed() method to populate the data. In my Database Context constructor I have this:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDBContext, Configuration>());
This works great, my database is automatically created with all the tables as I want, but it seems like the Seed() method is not being called, my database is empty. This is my class:
internal sealed class Configuration : DbMigrationsConfiguration<Context.MyDBContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(Context.MyDBContext context)
{
context.Users.AddOrUpdate(
new Entities.User() { Email = "default#default.com", Password = "", Language = "en", CreatedDate = DateTime.Now }
);
base.Seed(context);
}
}
When I run Update-Database in the Nuget console the data is populated after database creation, but with MigrateDatabaseToLatestVersion the Seed() method is not called.
What can be happening? I tried manually running migrations as taken from here:
var configuration = new MyDbContextConfiguration();
configuration.TargetDatabase = new DbConnectionInfo(
database.ConnectionString, database.ProviderName);
var migrator = new DbMigrator(configuration);
migrator.Update();
But also doesn't work.
EDIT:
Ok, after some more testing I found that the Seed() method runs but only when the database already exists, that is, on the first run when the database is created for the first time the Seed() method is not executed, but when I run my app the second time Seed() get's executed. I also had to add context.SaveChanges() in order for it to work (thanks to #DavidG in the comments):
protected override void Seed(Context.MyDBContext context)
{
context.Users.AddOrUpdate(
new Entities.User() { Email = "default#default.com", Password = "", Language = "en", CreatedDate = DateTime.Now }
);
context.SaveChanges();
base.Seed(context);
}
So maybe I can manually call Seed() inside Configuration() and do some checking to avoid adding duplicating data or modifying data that already exists.

I ended up with this Configuration class:
public class Configuration : DbMigrationsConfiguration<Context.MyDBContext>
{
private readonly bool _pendingMigrations;
public Configuration()
{
AutomaticMigrationsEnabled = true;
// Check if there are migrations pending to run, this can happen if database doesn't exists or if there was any
// change in the schema
var migrator = new DbMigrator(this);
_pendingMigrations = migrator.GetPendingMigrations().Any();
// If there are pending migrations run migrator.Update() to create/update the database then run the Seed() method to populate
// the data if necessary
if (_pendingMigrations)
{
migrator.Update();
Seed(new Context.MyDBContext());
}
}
protected override void Seed(Context.MyDBContext context)
{
// Microsoft comment says "This method will be called after migrating to the latest version."
// However my testing shows that it is called every time the software starts
// Run whatever you like here
// Apply changes to database
context.SaveChanges();
base.Seed(context);
}
}
So on this way the Seed() method is called when the database is created and also when there are pending migrations.
This is my MyDBContext class:
public class MyDBContext: DbContext
{
public MyDBContext() : base(AppSettings.DBConnectionString)
{
}
public static MyDBContext Create()
{
return new MyDBContext();
}
public DbSet<User> Users { get; set; }
public DbSet<Entries> Entries { get; set; }
}

Related

Dynamically changing schema in Entity Framework Core

UPD here is the way I solved the problem. Although it's likely to be not the best one, it worked for me.
I have an issue with working with EF Core. I want to separate data for different companies in my project's database via schema-mechanism. My question is how I can change the schema name in runtime? I've found similar question about this issue but it's still unanswered and I have some different conditions. So I have the Resolve method that grants the db-context when necessary
public static void Resolve(IServiceCollection services) {
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<DomainDbContext>()
.AddDefaultTokenProviders();
services.AddTransient<IOrderProvider, OrderProvider>();
...
}
I can set the schema-name in OnModelCreating, but, as was found before, this method is called just once, so I can set schema name globaly like that
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.HasDefaultSchema("public");
base.OnModelCreating(modelBuilder);
}
or right in the model via an attribute
[Table("order", Schema = "public")]
public class Order{...}
But how can I change the schema name on runtime? I create the context per each request, but first I fugure out the schema-name of the user via a request to a schema-shared table in the database. So what is the right way to organize that mechanism:
Figure out the schema name by the user credentials;
Get user-specific data from database from specific schema.
Thank you.
P.S. I use PostgreSql and this is the reason for lowecased table names.
Did you already use EntityTypeConfiguration in EF6?
I think the solution would be use mapping for entities on OnModelCreating method in DbContext class, something like this:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal;
using Microsoft.Extensions.Options;
namespace AdventureWorksAPI.Models
{
public class AdventureWorksDbContext : Microsoft.EntityFrameworkCore.DbContext
{
public AdventureWorksDbContext(IOptions<AppSettings> appSettings)
{
ConnectionString = appSettings.Value.ConnectionString;
}
public String ConnectionString { get; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConnectionString);
// this block forces map method invoke for each instance
var builder = new ModelBuilder(new CoreConventionSetBuilder().CreateConventionSet());
OnModelCreating(builder);
optionsBuilder.UseModel(builder.Model);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.MapProduct();
base.OnModelCreating(modelBuilder);
}
}
}
The code on OnConfiguring method forces the execution of MapProduct on each instance creation for DbContext class.
Definition of MapProduct method:
using System;
using Microsoft.EntityFrameworkCore;
namespace AdventureWorksAPI.Models
{
public static class ProductMap
{
public static ModelBuilder MapProduct(this ModelBuilder modelBuilder, String schema)
{
var entity = modelBuilder.Entity<Product>();
entity.ToTable("Product", schema);
entity.HasKey(p => new { p.ProductID });
entity.Property(p => p.ProductID).UseSqlServerIdentityColumn();
return modelBuilder;
}
}
}
As you can see above, there is a line to set schema and name for table, you can send schema name for one constructor in DbContext or something like that.
Please don't use magic strings, you can create a class with all available schemas, for example:
using System;
public class Schemas
{
public const String HumanResources = "HumanResources";
public const String Production = "Production";
public const String Sales = "Sales";
}
For create your DbContext with specific schema you can write this:
var humanResourcesDbContext = new AdventureWorksDbContext(Schemas.HumanResources);
var productionDbContext = new AdventureWorksDbContext(Schemas.Production);
Obviously you should to set schema name according schema's name parameter's value:
entity.ToTable("Product", schemaName);
Define your context and pass the schema to the constructor.
In OnModelCreating Set the default schema.
public class MyContext : DbContext , IDbContextSchema
{
private readonly string _connectionString;
public string Schema {get;}
public MyContext(string connectionString, string schema)
{
_connectionString = connectionString;
Schema = schema;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.ReplaceService<IModelCacheKeyFactory, DbSchemaAwareModelCacheKeyFactory>();
optionsBuilder.UseSqlServer(_connectionString);
}
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(Schema);
// ... model definition ...
}
}
Implement your IModelCacheKeyFactory.
public class DbSchemaAwareModelCacheKeyFactory : IModelCacheKeyFactory
{
public object Create(DbContext context)
{
return new {
Type = context.GetType(),
Schema = context is IDbContextSchema schema
? schema.Schema
: null
};
}
}
In OnConfiguring replace the default implementation of IModelCacheKeyFactory with your custom implementation.
With the default implementation of IModelCacheKeyFactory the method OnModelCreating is executed only the first time the context is instantiated and then the result is cached.
Changing the implementation you can modify how the result of OnModelCreating is cached and retrieve. Including the schema in the caching key you can get the OnModelCreating executed and cached for every different schema string passed to the context constructor.
// Get a context referring SCHEMA1
var context1 = new MyContext(connectionString, "SCHEMA1");
// Get another context referring SCHEMA2
var context2 = new MyContext(connectionString, "SCHEMA2");
Sorry everybody, I should've posted my solution before, but for some reason I didn't, so here it is.
BUT
Keep in mind that anything could be wrong with the solution since it neither hasn't been reviewed by anybody nor production-proved, probably I'll get some feedback here.
In the project I used ASP .NET Core 1
About my db structure. I have 2 contexts. The first one contains information about users (including the db scheme they should address), the second one contains user-specific data.
In Startup.cs I add both contexts
public void ConfigureServices(IServiceCollection
services.AddEntityFrameworkNpgsql()
.AddDbContext<SharedDbContext>(options =>
options.UseNpgsql(Configuration["MasterConnection"]))
.AddDbContext<DomainDbContext>((serviceProvider, options) =>
options.UseNpgsql(Configuration["MasterConnection"])
.UseInternalServiceProvider(serviceProvider));
...
services.Replace(ServiceDescriptor.Singleton<IModelCacheKeyFactory, MultiTenantModelCacheKeyFactory>());
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Notice UseInternalServiceProvider part, it was suggested by Nero Sule with the following explanation
At the very end of EFC 1 release cycle, the EF team decided to remove EF's services from the default service collection (AddEntityFramework().AddDbContext()), which means that the services are resolved using EF's own service provider rather than the application service provider.
To force EF to use your application's service provider instead, you need to first add EF's services together with the data provider to your service collection, and then configure DBContext to use internal service provider
Now we need MultiTenantModelCacheKeyFactory
public class MultiTenantModelCacheKeyFactory : ModelCacheKeyFactory {
private string _schemaName;
public override object Create(DbContext context) {
var dataContext = context as DomainDbContext;
if(dataContext != null) {
_schemaName = dataContext.SchemaName;
}
return new MultiTenantModelCacheKey(_schemaName, context);
}
}
where DomainDbContext is the context with user-specific data
public class MultiTenantModelCacheKey : ModelCacheKey {
private readonly string _schemaName;
public MultiTenantModelCacheKey(string schemaName, DbContext context) : base(context) {
_schemaName = schemaName;
}
public override int GetHashCode() {
return _schemaName.GetHashCode();
}
}
Also we have to slightly change the context itself to make it schema-aware:
public class DomainDbContext : IdentityDbContext<ApplicationUser> {
public readonly string SchemaName;
public DbSet<Foo> Foos{ get; set; }
public DomainDbContext(ICompanyProvider companyProvider, DbContextOptions<DomainDbContext> options)
: base(options) {
SchemaName = companyProvider.GetSchemaName();
}
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.HasDefaultSchema(SchemaName);
base.OnModelCreating(modelBuilder);
}
}
and the shared context is strictly bound to shared schema:
public class SharedDbContext : IdentityDbContext<ApplicationUser> {
private const string SharedSchemaName = "shared";
public DbSet<Foo> Foos{ get; set; }
public SharedDbContext(DbContextOptions<SharedDbContext> options)
: base(options) {}
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.HasDefaultSchema(SharedSchemaName);
base.OnModelCreating(modelBuilder);
}
}
ICompanyProvider is responsible for getting users schema name. And yes, I know how far from the perfect code it is.
public interface ICompanyProvider {
string GetSchemaName();
}
public class CompanyProvider : ICompanyProvider {
private readonly SharedDbContext _context;
private readonly IHttpContextAccessor _accesor;
private readonly UserManager<ApplicationUser> _userManager;
public CompanyProvider(SharedDbContext context, IHttpContextAccessor accesor, UserManager<ApplicationUser> userManager) {
_context = context;
_accesor = accesor;
_userManager = userManager;
}
public string GetSchemaName() {
Task<ApplicationUser> getUserTask = null;
Task.Run(() => {
getUserTask = _userManager.GetUserAsync(_accesor.HttpContext?.User);
}).Wait();
var user = getUserTask.Result;
if(user == null) {
return "shared";
}
return _context.Companies.Single(c => c.Id == user.CompanyId).SchemaName;
}
}
And if I haven't missed anything, that's it. Now in every request by an authenticated user the proper context will be used.
I hope it helps.
There are a couple ways to do this:
Build the model externally and pass it in via DbContextOptionsBuilder.UseModel()
Replace the IModelCacheKeyFactory service with one that takes the schema into account
Took several hours to figure this out with EFCore. Seems to be alot of confusion on the proper way of implementing this. I believe the simple and correct way of handling custom models in EFCore is replacing the default IModelCacheKeyFactory service like I show below. In my example I am setting custom table names.
Create a ModelCacheKey variable in your context class.
In your context constructor, set the ModelCacheKey variable
Create a class that inherits from IModelCacheKeyFactory and use ModelCacheKey (MyModelCacheKeyFactory)
In OnConfiguring method (MyContext), replace the default IModelCacheKeyFactory
In OnModelCreating method (MyContext), use the ModelBuilder to define whatever you need.
public class MyModelCacheKeyFactory : IModelCacheKeyFactory
{
public object Create(DbContext context)
=> context is MyContext myContext ?
(context.GetType(), myContext.ModelCacheKey) :
(object)context.GetType();
}
public partial class MyContext : DbContext
{
public string Company { get; }
public string ModelCacheKey { get; }
public MyContext(string connectionString, string company) : base(connectionString)
{
Company = company;
ModelCacheKey = company; //the identifier for the model this instance will use
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//This will create one model cache per key
optionsBuilder.ReplaceService<IModelCacheKeyFactory, MyModelCacheKeyFactory();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>(entity =>
{
//regular entity mapping
});
SetCustomConfigurations(modelBuilder);
}
public void SetCustomConfigurations(ModelBuilder modelBuilder)
{
//Here you will set the schema.
//In my example I am setting custom table name Order_CompanyX
var entityType = typeof(Order);
var tableName = entityType.Name + "_" + this.Company;
var mutableEntityType = modelBuilder.Model.GetOrAddEntityType(entityType);
mutableEntityType.RemoveAnnotation("Relational:TableName");
mutableEntityType.AddAnnotation("Relational:TableName", tableName);
}
}
The result is each instance of your context will cause efcore to cache based on the ModelCacheKey variable.
I find this blog might be useful for you. Perfect !:)
https://romiller.com/2011/05/23/ef-4-1-multi-tenant-with-code-first/
This blog is based on ef4, I'm not sure whether it will work fine with ef core.
public class ContactContext : DbContext
{
private ContactContext(DbConnection connection, DbCompiledModel model)
: base(connection, model, contextOwnsConnection: false)
{ }
public DbSet<Person> People { get; set; }
public DbSet<ContactInfo> ContactInfo { get; set; }
private static ConcurrentDictionary<Tuple<string, string>, DbCompiledModel> modelCache
= new ConcurrentDictionary<Tuple<string, string>, DbCompiledModel>();
/// <summary>
/// Creates a context that will access the specified tenant
/// </summary>
public static ContactContext Create(string tenantSchema, DbConnection connection)
{
var compiledModel = modelCache.GetOrAdd(
Tuple.Create(connection.ConnectionString, tenantSchema),
t =>
{
var builder = new DbModelBuilder();
builder.Conventions.Remove<IncludeMetadataConvention>();
builder.Entity<Person>().ToTable("Person", tenantSchema);
builder.Entity<ContactInfo>().ToTable("ContactInfo", tenantSchema);
var model = builder.Build(connection);
return model.Compile();
});
return new ContactContext(connection, compiledModel);
}
/// <summary>
/// Creates the database and/or tables for a new tenant
/// </summary>
public static void ProvisionTenant(string tenantSchema, DbConnection connection)
{
using (var ctx = Create(tenantSchema, connection))
{
if (!ctx.Database.Exists())
{
ctx.Database.Create();
}
else
{
var createScript = ((IObjectContextAdapter)ctx).ObjectContext.CreateDatabaseScript();
ctx.Database.ExecuteSqlCommand(createScript);
}
}
}
}
The main idea of these codes is to provide a static method to create different DbContext by different schema and cache them with certain identifiers.
You can use Table attribute on the fixed schema tables.
You can't use attribute on schema changing tables and you need to configure that via ToTable fluent API.
If you disable the model cache (or you write your own cache), the schema can change on every request so on the context creation (every time) you can to specify the schema.
This is the base idea
class MyContext : DbContext
{
public string Schema { get; private set; }
public MyContext(string schema) : base()
{
}
// Your DbSets here
DbSet<Emp> Emps { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Emp>()
.ToTable("Emps", Schema);
}
}
Now, you can have some different ways to determine the schema name before creating the context.
For example you can have your "system tables" on a different context so on every request you retrieve the schema name from the user name using the system tables and than create the working context on the right schema (you can share tables between contexts).
You can have your system tables detached from the context and use ADO .Net to access to them.
Probably there are several other solutions.
You can also have a look here
Multi-Tenant With Code First EF6
and you can google ef multi tenant
EDIT
There is also the problem of the model caching (I forgot about that).
You have to disable the model caching or change the behavior of the cache.
maybe I'm a bit late to this answer
my problem was handling different schema with the same structure lets say multi-tenant.
When I tried to create different instances of the same context for the different schemas, Entity frameworks 6 comes to play, catching the first time the dbContext was created then for the following instances they were creates with a different schemas name but onModelCreating were never called meaning that each instance was pointing to the same previously catched Pre-Generated Views, pointing to the first schema.
Then I realized that creating new classes inheriting from myDBContext one for each schema will solve my problem by overcoming entity Framework catching problem creating one new fresh context for each schema, but then comes the problem that we will end with hardcoded schemas, causing another problem in terms of code scalability when we need to add another schema, having to add more classes and recompile and publish a new version of the application.
So I decided to go a little further creating, compiling and adding the classes to the current solution in runtime.
Here is the code
public static MyBaseContext CreateContext(string schema)
{
MyBaseContext instance = null;
try
{
string code = $#"
namespace MyNamespace
{{
using System.Collections.Generic;
using System.Data.Entity;
public partial class {schema}Context : MyBaseContext
{{
public {schema}Context(string SCHEMA) : base(SCHEMA)
{{
}}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{{
base.OnModelCreating(modelBuilder);
}}
}}
}}
";
CompilerParameters dynamicParams = new CompilerParameters();
Assembly currentAssembly = Assembly.GetExecutingAssembly();
dynamicParams.ReferencedAssemblies.Add(currentAssembly.Location); // Reference the current assembly from within dynamic one
// Dependent Assemblies of the above will also be needed
dynamicParams.ReferencedAssemblies.AddRange(
(from holdAssembly in currentAssembly.GetReferencedAssemblies()
select Assembly.ReflectionOnlyLoad(holdAssembly.FullName).Location).ToArray());
// Everything below here is unchanged from the previous
CodeDomProvider dynamicLoad = CodeDomProvider.CreateProvider("C#");
CompilerResults dynamicResults = dynamicLoad.CompileAssemblyFromSource(dynamicParams, code);
if (!dynamicResults.Errors.HasErrors)
{
Type myDynamicType = dynamicResults.CompiledAssembly.GetType($"MyNamespace.{schema}Context");
Object[] args = { schema };
instance = (MyBaseContext)Activator.CreateInstance(myDynamicType, args);
}
else
{
Console.WriteLine("Failed to load dynamic assembly" + dynamicResults.Errors[0].ErrorText);
}
}
catch (Exception ex)
{
string message = ex.Message;
}
return instance;
}
I hope this help someone to save some time.
Update for MVC Core 2.1
You can create a model from a database with multiple schemas. The system is a bit schema-agnostic in its naming. Same named tables get a "1" appended. "dbo" is the assumed schema so you don't add anything by prefixing a table name with it the PM command
You will have to rename model file names and class names yourself.
In the PM console
Scaffold-DbContext "Data Source=localhost;Initial Catalog=YourDatabase;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force -Tables TableA, Schema1.TableA
I actually found it to be a simpler solution with an EF interceptor.
I actually keep the onModeling method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("dbo"); // this is important to always be dbo
// ... model definition ...
}
And this code will be in Startup:
public void ConfigureServices(IServiceCollection services)
{
// if I add a service I can have the lambda (factory method) to read from request the schema (I put it in a cookie)
services.AddScoped<ISchemeInterceptor, SchemeInterceptor>(provider =>
{
var context = provider.GetService<IHttpContextAccessor>().HttpContext;
var scheme = "dbo";
if (context.Request.Cookies["schema"] != null)
{
scheme = context.Request.Cookies["schema"];
}
return new SchemeInterceptor(scheme);
});
services.AddDbContext<MyContext>(options =>
{
var sp = services.BuildServiceProvider();
var interceptor = sp.GetService<ISchemeInterceptor>();
options.UseSqlServer(Configuration.GetConnectionString("Default"))
.AddInterceptors(interceptor);
});
And the interceptor code looks something like this (but basically we use ReplaceSchema):
public interface ISchemeInterceptor : IDbCommandInterceptor
{
}
public class SchemeInterceptor : DbCommandInterceptor, ISchemeInterceptor
{
private readonly string _schema;
public SchemeInterceptor(string schema)
{
_schema = schema;
}
public override Task<InterceptionResult<object>> ScalarExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<object> result,
CancellationToken cancellationToken = new CancellationToken())
{
ReplaceSchema(command);
return base.ScalarExecutingAsync(command, eventData, result, cancellationToken);
}
public override InterceptionResult<object> ScalarExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<object> result)
{
ReplaceSchema(command);
return base.ScalarExecuting(command, eventData, result);
}
public override Task<InterceptionResult<int>> NonQueryExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<int> result,
CancellationToken cancellationToken = new CancellationToken())
{
ReplaceSchema(command);
return base.NonQueryExecutingAsync(command, eventData, result, cancellationToken);
}
public override InterceptionResult<int> NonQueryExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<int> result)
{
ReplaceSchema(command);
return base.NonQueryExecuting(command, eventData, result);
}
public override InterceptionResult<DbDataReader> ReaderExecuting(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result)
{
ReplaceSchema(command);
return result;
}
public override Task<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = new CancellationToken())
{
ReplaceSchema(command);
return base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
}
private void ReplaceSchema(DbCommand command)
{
command.CommandText = command.CommandText.Replace("[dbo]", $"[{_schema}]");
}
public override void CommandFailed(DbCommand command, CommandErrorEventData eventData)
{
// here you can handle cases like schema not found
base.CommandFailed(command, eventData);
}
public override Task CommandFailedAsync(DbCommand command, CommandErrorEventData eventData,
CancellationToken cancellationToken = new CancellationToken())
{
// here you can handle cases like schema not found
return base.CommandFailedAsync(command, eventData, cancellationToken);
}
}
If the only difference between databases is schema name the simplest way to get rid of the problem is to remove line of code which is setting the default schema in OnModelCreating method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
...
modelBuilder.HasDefaultSchema("YourSchemaName"); <-- remove or comment this line
...
}
In this case underneeth sql queries run by EF Core won't contain schema name in their FROM clause. Then you will be able to write a method which will set correct DbContext depending on your custom conditions.
Here is an example which I used to connect to different Oracle databases with the same database structure (in short let's say that in Oracle schema is the same as user). If you're using another DB you just need to put correct connection string and then modify it.
private YourDbContext SetDbContext()
{
string connStr = #"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=server_ip)(PORT=1521)))(CONNECT_DATA=(SID = server_sid)));User Id=server_user ;Password=server_password";
//You can get db connection details e.g. from app config
List<string> connections = config.GetSection("DbConneections");
string serverIp;
string dbSid;
string dBUser;
string dbPassword;
/* some logic to choose a connection from config and set up string variables for a connection*/
connStr = connStr.Replace("server_ip", serverIp);
connStr = connStr.Replace("server_sid", dbSid);
connStr = connStr.Replace("server_user", dBUser);
connStr = connStr.Replace("server_password", dbPassword);
var dbContext = dbContextFactory.CreateDbContext();
dbContext.Database.CloseConnection();
dbContext.Database.SetConnectionString(connStr);
return dbContext;
}
Finally you will be able to set desired dbContext where it's needed invoking this method before, you can also pass some arguments to the method to help you choose correct db.

How to change the record created as a one-to-one relation to itself Entity Framework 7 (ASP.NET Core)?

I use EntityFramework 7 RC1 in the project ASP.NET 5 MVC 6 RC 1
I do not work change roles (each role has a parent). Below is a simplified example of what I'm trying to do. This code runs successfully and does not cause errors.
var roleDb = roleManager.FindByNameAsync("UserRole").Result;
var searchRoleDb = roleManager.FindByNameAsync("AdminRole").Result;
if (roleDb != null)
{
roleDb.DateEdit = DateTime.Now;
if (searchRoleDb != null)
{
roleDb.Parent = searchRoleDb;
}
context.Entry(roleDb).State = EntityState.Modified;
context.SaveChanges();
}
But ParentId field in the database remains null.
public class ApplicationRole : IdentityRole
{
...
public string ParentId { get; set; }
public virtual ApplicationRole Parent { get; set; }
...
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ApplicationRole>()
.HasOne(c => c.Parent)
.WithMany()
.HasForeignKey(c => c.ParentId);
}
}
I have also successfully changed the other data in the database, as well as the successful use of data migration.
I can not just change the value ParentId.
As I mentioned in my initial comment, you should use the asp.net Identity RoleManager class when making changes to the role since you're using it to retrieve the roles as part of the change. You could use your context to do it manually/directly but this is effectively bypassing asp.net identity. Here is an updated version of your original sample using RoleManager to perform the update:
public async Task UpdateRole()
{
var roleDb = await roleManager.FindByNameAsync("UserRole");
var searchRoleDb = await roleManager.FindByNameAsync("AdminRole");
if (roleDb != null)
{
roleDb.DateEdit = DateTime.Now;
if (searchRoleDb != null)
{
roleDb.Parent = searchRoleDb;
}
await roleManager.UpdateAsync(roleDb);
}
}
I've also updated the FindByNameAsync calls to use "await" rather than ".Result" to avoid the potential deadlock issue I mentioned. However for this to work the method signature must return a Task and include the "async" modifier. For help with the asynchronous stuff I recommend starting here
Edit
Based on the comment with regards to seeding, I normally seed my roles like this:
internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
protected override void Seed(MyDbContext context)
{
SeedRoles(context);
}
private static void SeedRoles(MyDbContext context)
{
var manager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
CreateRoleIfNotExists(manager, "Role1");
CreateRoleIfNotExists(manager, "Role2");
}
private static void CreateRoleIfNotExists(RoleManager<IdentityRole> manager, string role)
{
if (!manager.RoleExists(role)
{
manager.Create(new IdentityRole(role));
}
}
}
You'll need to update the code with your Context, User and Role classes as I've just used the defaults.
There is no need to explicitly save the changes as this is done by the DbContext class when the call to Seed() returns/completes. With this approach there are no async calls so you don't need to worry about any of the issues I mentioned with regards to that.
This is because the roleManager uses a different context than you use for database modifications. You should get the role through the context and modify it then.
var roleDb = context.Set<IdentityRole>().FirstOrDefault(x => x.Name == "UserRole");
var searchRoleDb = context.Set<IdentityRole>().FirstOrDefault(x => x.Name == "AdminRole");
if (roleDb != null)
{
roleDb.DateEdit = DateTime.Now;
context.SaveChanges();
}

Entity Framework code first - initial code migration not working

I am trying to run migrations from code. I created my models and enabled-migrations and then added initial migration, this initial migration contains all the create tables etc
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(..........
}
public override void Down()
{
DropTable(...........
}
}
I then tried the Update-Database command from the visual studio which works fine, creates the database and runs the initial migration.
I then delete the database from the Sql Studio. Then I run the console app that calls the Migration Manager class
// MigrationManager class
public static bool PerformMigration(string migrationId)
{
bool success = false;
try
{
DbMigrationsConfiguration<MyDbContext> config = new Configuration();
....
DbMigrator migrator = new DbMigrator(config);
migrator.Configuration.AutomaticMigrationsEnabled = false;
if (string.IsNullOrEmpty(migrationId))
migrator.Update(); --> fails saying pending migration
else
migrator.Update(migrationId);
success = true;
}
catch (Exception e)
{
success = false;
LastException = e.Message;
}
return success;
}
The Update() fails with the following error:
Unable to update database to match the current model because there are pending changes and automatic migration is disabled.
Either write the pending model changes to a code-based migration or enable automatic migration.
Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
//Configuration.cs
internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(WorkflowConfigurationDbContext context)
{
SeedData(context);
}
private void SeedData(){...}
}
public class MyDbContext : DbContext
{
public MyDbContext()
{
}
public DbSet....
}
When I step through the Update() call, it goes into Configuration() constructor and MyDbContext() constructor but fails after that, it seems like its not trying the Initial migration at all.
Make sure the database initialization strategy is correct in your EF context's constructor, like:
public partial class YourContext: DbContext
{
static YourContext()
{
Database.SetInitializer<YourContext>(new CreateDatabaseIfNotExists<YourContext>());
}
}
This is executed the first time the database is accessed.
EDIT: A second issue may be about security: does the user that is executing the migration have the required permissions?
Found the issue, it was incorrect namespace.
DbMigrationsConfiguration<MyDbContext> config = new Configuration();
config.MigrationsNamespace = "Correct Namespace";

Entity Framework: Running code before all migrations

I want to migrate stored procedures and views in my DB. Since I always migrate to the latest version, a source-control-friendly approach is to drop/recreate all procedures/views during migration process (with this approach there is one file per procedure, instead of one-per-version).
Since old procedures/functions/views might not be compatible with new schema changes, I want to do drop before all migrations, then do the create after all.
Previously I used a customized FluentMigrator, but now I am researching Entity Framework Code First Migrations. I see that I can use Seed to always run code after all migrations.
Is there something I can use to always run code before all migrations?
If you want some code to run before migrations kick in, you can specify a custom database initializer:
public class AwesomeEntity
{
public int Id { get; set; }
}
public class AwesomeDbContext : DbContext
{
static AwesomeDbContext()
{
Database.SetInitializer(new AwesomeDatabaseInitializer());
}
public IDbSet<AwesomeEntity> Entities { get; set; }
}
public class AwesomeDatabaseInitializer : MigrateDatabaseToLatestVersion<AwesomeDbContext, AwesomeMigrationsConfiguration>
{
public override void InitializeDatabase(AwesomeDbContext context)
{
// TODO: Run code before migration here...
base.InitializeDatabase(context);
}
}
public class AwesomeMigrationsConfiguration : DbMigrationsConfiguration<AwesomeDbContext>
{
public AwesomeMigrationsConfiguration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(AwesomeDbContext context)
{
// TODO: Seed database here...
}
}
This sets the custom initializer to a custom AwesomeDatabaseInitializer, which inherits from MigrateDatabaseToLatestVersion. If you want to drop and rebuild the database every time, you should use the DropCreateDatabaseAlways as base class instead, though I'm not sure this lets you run migrations.
In the initializer, you can override the InitializeDatabase method, where you can run code before you call base.InitializeDatabase, which will trigger the database initialization and in turn the Seed method of the migration configuration, AwesomeMigrationsConfiguration.
This is using EF6. I'm not sure if there is an equivalent in earlier versions of entity framework.
I have a solution that is pretty horrible, but works for migrate.exe.
Here is the idea:
Use Seed for AfterAll, as suggested by #khellang.
For BeforeAll, register a custom IDbConnectionInterceptor in MigrationsConfiguration constuctor to capture first connection after the MigrationsConfiguration has been created, then make it unregister itself. Obviously this is absolutely not thread-safe and only OK in application startup or migrate.exe.
Example code:
public class DbMigrationsInterceptingConfiguration<TContext> : DbMigrationsConfiguration<TContext>
where TContext : DbContext
{
public DbMigrationsInterceptingConfiguration() {
BeforeFirstConnectionInterceptor.InterceptNext();
}
protected override void Seed(TContext context) {
Console.WriteLine("After All!");
}
}
internal class BeforeFirstConnectionInterceptor : IDbConnectionInterceptor {
public static void InterceptNext() {
DbInterception.Add(new BeforeFirstConnectionInterceptor());
}
public void Opened(DbConnection connection, DbConnectionInterceptionContext interceptionContext) {
// NOT thread safe
Console.WriteLine("Before All!");
DbInterception.Remove(this);
}
// ... empty implementation of other methods in IDbConnectionInterceptor
}
I am not sure I would be actually using it though.

Seed method not called, Entity Framework 6

I have a DatabaseInitializer class
public class DatabaseInitializer : CreateDatabaseIfNotExists<DatabaseContext>
{
protected override void Seed
(
DatabaseContext databaseContext
)
{
// Seed the hash methods.
var defaultHashMethod = new HashMethod
{
Description = "Default",
CreateDate = DateTime.Now
};
databaseContext.HashMethod.Add(defaultHashMethod);
databaseContext.SaveChanges();
}
}
In my DatabaseContext class I set the initializer
public DatabaseContext() : base("DatabaseContext")
{
InitializeDatabase();
}
private void InitializeDatabase()
{
Database.SetInitializer(new DatabaseInitializer());
if (!Database.Exists())
{
Database.Initialize(true);
}
}
As far as I can understand the seed method is only invoked once you perform an operation such as a query. My database is created successfully and I'm querying the table, but the seed method is never called.
Update:
It seems like the problem is caused because of a class that is inheriting from my DatabaseContext class, when using this class to perform database operations, the seed method is not called. When using my DatabaseContext class, everything works as expected
public DbSet<TestEntity> TestEntity { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
You need to call Update-Database from the Package Manager Console.
The only way I could get this to work was to call the seed method myself
Here are the methods for my DatabaseContext class
public DatabaseContext() : base("DatabaseContext")
{
InitializeDatabase();
}
public DatabaseContext(string connectionString) : base(connectionString)
{
Database.Connection.ConnectionString = connectionString;
InitializeDatabase();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
Here I changed my InitializeDatabase method from
private void InitializeDatabase()
{
Database.SetInitializer(new DatabaseInitializer());
if (!Database.Exists())
{
Database.Initialize(true);
}
}
to
protected virtual void InitializeDatabase()
{
if (!Database.Exists())
{
Database.Initialize(true);
new DatabaseInitializer().Seed(this);
}
}
This can happen if your Update-Database command does not run successfully, and this does not necessarily mean that it errors out. There might be changes that EF recognizes as "outstanding" that need to be added to a migration.
Try calling "Add-Migration {migrationNameHere}" and then try "Update-Database" again.
to get Seed method to be called when you are not using AutomaticMigration, you should use MigrateDatabaseToLatestVersion initializer for your code-first database.
like this:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<YourContext,YourConfiguration>());
this way, Seed method will be called every time the migration is done successfully.
I had this issue and the problem was my Context constructor did not use the same name as in my web.config.
If you are using Code-First then you can populate the data when the application runs for the first time.
Create a DbInitializer
public class MyDbInitializer : IDatabaseInitializer<MyDbContext>
{
public void InitializeDatabase(MyDbContext context)
{
if (context.Database.Exists())
{
if (!context.Database.CompatibleWithModel(true))
{
context.Database.Delete();
}
}
context.Database.Create();
User myUser = new User()
{
Email = "a#b.com",
Password = "secure-password"
};
context.Users.AddOrUpdate<User>(p => p.Email, myUser);
context.SaveChanges();
}
}
Register this DbInitializer in your Global.asax.cs Application_Start method
Database.SetInitializer(new My.namespace.MyDbInitializer());
My seed was not being executed either. However, it was because I added a column to a model that I had no intention of using in my actual database and forgot to use the [NotMapped] annotation.
[NotMapped]
public string Pair { get; set; }
There was no error message relating to this being the cause at all. Just a null reference to my repository obj when I tried to query data that should have been there.

Categories

Resources