I am trying to unit test with the EF Core in-memory database like so:
namespace ContosoTests
{
public class TrendServiceTests
{
private static Microsoft.EntityFrameworkCore.DbContextOptions<TestContext> options = new
Microsoft.EntityFrameworkCore.DbContextOptionsBuilder<TestContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
private static TestContext _context = new TestContext(options);
private readonly TrendService trendService = new TrendService(_context);
private void SeedInMemoryDb()
{
if (!_context.TrendHistories.Any())
{
_context.TrendHistories.Add(new TrendHistory { IsActive = true, Quarter = E_Quarter.Q1,
TrendYear = 2020 });
}
if (!_context.Controls.Any())
{
_context.Controls.Add(new Control { IsActive = true});
_context.Controls.Add(new Control { IsActive = true});
_context.Controls.Add(new Control { IsActive = false});
}
_context.SaveChanges();
}
}
My TestContext inherits from my live context class to avoid the error:
Services for database providers 'Microsoft.EntityFrameworkCore.InMemory', 'Microsoft.EntityFrameworkCore.SqlServer' have been registered in the service provider. Only a single database provider can be registered in a service provider
So my TestContext just looks like:
public class TestContext : ContosoContext
{
public TestContext(DbContextOptions<TestContext> options)
{
}
public TestContext()
{
}
}
When I use the new instance of TestContext (_context) in my test class, all the live data for ContosoContext is there.
I was expecting it to be a new instance of the context class with no data so that I could test my DAL code with controlled data. But this is not the case.
I am fairly new to unit testing so any help is much appreciated.
Edit:
Here are the relevant parts of my contoso context class
public class ContosoContext: IdentityDbContext<ContosoApplicationUser>
{
public ContosoContext(DbContextOptions<ContosoContext> options) : base
(options)
{
}
public ContosoContext()
{
}
//all my DBSets here
protected override void OnConfiguring(DbContextOptionsBuilder
optionsBuilder)
{
optionsBuilder.UseSqlServer("MyConnectionString");
}
}
So the issue is that my onconfiguring method handles the connection string directly??
To fix the error you need to remove optionsBuilder.UseSqlServer("MyConnectionString"); in OnConfiguring method to avoid registering multiple database providers, change it to this:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if(!optionsBuilder.IsConfigured)
optionsBuilder.UseSqlServer("MyConnectionString");
}
I have a DbMigrationsConfiguration that looks like this:
internal sealed class Configuration : DbMigrationsConfiguration<DatabaseProject.DB>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = false;
}
}
Elsewhere, in my DbContext class I have:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DB, DbProject.Migrations.Configuration>(useSuppliedContext: true));
// and so on...
And I want to use the MigrationsLogger to record some information when a migration is applied. So I set up a simple class like this using serilog:
public class EfLogger : MigrationsLogger
{
public override void Info(string message)
{
Log.Logger.Information("Machine {name} reported EF Migration Message: {message}", Environment.MachineName,
message);
}
public override void Warning(string message)
{
Log.Logger.Warning("Machine {name} reported EF Migration Warning: {message}", Environment.MachineName,
message);
}
public override void Verbose(string message)
{
Log.Logger.Verbose("Machine {name} reported EF Migration verbose message: {message}", Environment.MachineName,
message);
}
}
So how do I change my configuration to use the new logger? I can't find any examples or documentation on this anywhere.
I looked into how this works and I think you won't be able to use MigrateDatabaseToLatestVersion directly. You should be able to override it though. If you look into the actual logic there it's actually quite simple:
https://github.com/dotnet/ef6/blob/master/src/EntityFramework/MigrateDatabaseToLatestVersion%60.cs
public virtual void InitializeDatabase(TContext context)
{
Check.NotNull(context, "context");
var migrator = new DbMigrator(_config, _useSuppliedContext ? context : null);
migrator.Update();
}
To add your logging to it, create a new MigrateDatabaseToLatestVersionWithLogging implementation that inherits from the standard MigrateDatabaseToLatestVersion, then override the method and introduce a logging decorator before calling update. Something like this (untested):
https://learn.microsoft.com/en-us/dotnet/api/system.data.entity.migrations.infrastructure.migratorloggingdecorator?view=entity-framework-6.2.0
public override void InitializeDatabase(TContext context)
{
_ = context ?? throw new ArgumentNullException(nameof(context));
var migrator = new MigratorLoggingDecorator(
new DbMigrator(_config, _useSuppliedContext ? context : null),
new EfLogger());
migrator.Update();
}
I'm trying to make an application that changes the DbConnection string based on the authenticated user.
So, after the user login, I have to get that user, see a field like "connectionName" and look for that connectionString on my app.config to connect to my database.
I already know how to set my Dependency Injection to pass the constructor params, but how do I get at my dependency injector Project the logged user ?
Something like this.
This is in a Project called "Project.Infra"
DBContext
public class MyDbContext : DbContext
{
//ConnectionStringBasedOnUserLogged will be a propertie on my userModel
//so I have to get the logged user before have it.
public MyDbContext(string ConnectionStringBasedOnUserLogged)
: base(ConnectionStringBasedOnUserLogged)
{
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
}
//DbSets...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Mappings...
}
}
This is in a Project called "Project.Infra"
Repository
public class MyRepository : IMyRepository
{
private MyDbContext _ctx;
public MyRepository(MyDbContextcontext)
{
this._ctx = context;
}
//Implementation of interface...
}
This is in a Project called "Project.Api"
Controller
public class MyController : ApiController
{
private IMyRepository _repo;
public MyController(IMyRepository repo)
{
this._repo = repo;
}
//Implementation
}
This is in a Project called "Project.Startup"ยด
DepencyInjection
public static class DependencyResolver
{
public static void Resolve(UnityContainer container)
{
//How do I get here some details about the logged user at my application ?
container.RegisterType<MyDbContext, MyDbContext>(new HierarchicalLifetimeManager(), new InjectionConstructor("HereWillComeTheConnection"));
container.RegisterType<IMyRepository, MyRepository>(new HierarchicalLifetimeManager()); }
}
Running Entity Framework 6.1 in a Web API application. I have my DatabaseContext setup and when I run Update-Database from the package manager console, the database creates and seeds correctly.
However, if I delete or manually create the database and then run the application, entity framework will create the tables in the database, but the seed methods to populate the data are not run. Anyone have any idea why the seed data would not be running? Code is below.
namespace MyProject.API.DBMigrations
{
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using MyProject.API.Infrastructure;
using MyProject.Models.Business_Models;
using MyProject.Models.Domain_Models;
using MyProject.Models.Models;
internal sealed class DatabaseConfiguration : DbMigrationsConfiguration<MyProject.API.Infrastructure.ApplicationDbContext>
{
public DatabaseConfiguration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
MigrationsDirectory = #"DBMigrations";
}
protected override void Seed(MyProject.API.Infrastructure.ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
DatabaseSeeder.SeedSecurity(context);
DatabaseSeeder.SeedBusiness(context);
base.Seed(context);
}
}
public class MyProjectDBInitializer : DropCreateDatabaseIfModelChanges<MyProject.API.Infrastructure.ApplicationDbContext>
{
// This Seed method is run when database is initialized if it is created if none exists
protected override void Seed(MyProject.API.Infrastructure.ApplicationDbContext context)
{
DatabaseSeeder.SeedBusiness(context);
DatabaseSeeder.SeedSecurity(context);
base.Seed(context);
}
}
public static class DatabaseSeeder
{
public static void SeedSecurity(MyProject.API.Infrastructure.ApplicationDbContext context)
{
//SEED Data added here (redacted for brevity)
}
public static void SeedBusiness(MyProject.API.Infrastructure.ApplicationDbContext context)
{
//SEED Data added here (redacted for brevity)
}
}
}
Here is part of my db context where I set the initializers. I've even tried setting the initializer in global.asax, but that didn't help.
namespace MyProject.API.Infrastructure
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
Configuration.LazyLoadingEnabled = true;
System.Data.Entity.Database.SetInitializer<ApplicationDbContext>(new MyProjectDBInitializer());
}
// no change: this static ctor called the first time this type is referenced
static ApplicationDbContext() {
System.Data.Entity.Database.SetInitializer<ApplicationDbContext>(new MyProjectDBInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Fluent api code here
// Add foreign key constraint here or else nullable doesn't work when EF does savechanges
modelBuilder.Entity<GiftCardTransaction>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
base.OnModelCreating(modelBuilder);
}
}
}
I'm utilizing Entity Framework 4.3 Migrations in my project. I would like to use Automatic migrations so that when I make modifications to my domain objects and my context class, my database automatically updates when I run the project. I have this working so far.
I would also like to use some Added Migrations in addition to the automatic migrations, and I would like the application to automatically jump to the latest version (based on my added migrations) when I run the application.
In order to do this I have placed this in the global.asax file...
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Core.Migrations.Configuration>());
Now this works, but when I do this it no longer automatically updates the database based on my domain objects.
I would like to be able to completely delete the database and then run the application and have all the automatic migrations run and then have my explicit migrations run and bring the database up to the latest version.
I know I've had this working in a previous project, but I'm not sure what I'm doing wrong in this instance.
Thanks
You need to pass a configuration that has the AutomaticMigrationsEnabled set to true in the constructor. Something like this should help:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, MyConfiguration>());
with MyConfiguration being something like:
public class MyConfiguration : Core.Migrations.Configuration
{
public MyConfiguration { this.AutomaticMigrationsEnabled = true; }
}
DISCLAIMER: Just hacked this in, so small tweaks might be required to get this to compile
EDIT:
Just checked with EF 4.3.1 and the code is like this for the initializer:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, MyConfiguration>());
and this for the configuration class:
public class MyConfiguration : System.Data.Entity.Migrations.DbMigrationsConfiguration<DataContext>
{
public MyConfiguration()
{
this.AutomaticMigrationsEnabled = true;
}
}
After banging my head on this for several hours, I finally came up with a solution that creates the database if necessary or upgrades it if out of date. We use this technique in Gallery Server Pro to make it easy to install the first time or upgrade previous versions.
private static void InitializeDataStore()
{
System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion<GalleryDb, GalleryDbMigrationConfiguration>());
var configuration = new GalleryDbMigrationConfiguration();
var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration);
if (migrator.GetPendingMigrations().Any())
{
migrator.Update();
}
}
public sealed class GalleryDbMigrationConfiguration : DbMigrationsConfiguration<GalleryDb>
{
protected override void Seed(GalleryDb ctx)
{
MigrateController.ApplyDbUpdates();
}
}
I wrote up a blog post with a few more details:
Using Entity Framework Code First Migrations to auto-create and auto-update an application
Same solution that Roger did but using an static constructor on the DbContext.
Full code below.... this allow the initialization code to live on the class itself and is self-invoked at the first instantiation of the DataDbContext class.
public partial class DataDbContext : DbContext
{
public DataDbContext()
: base("name=DefaultConnection")
{
}
static DataDbContext() // This is an enhancement to Roger's answer
{
Database.SetInitializer(new DataDbInitializer());
var configuration = new DataDbConfiguration();
var migrator = new DbMigrator(configuration);
if (migrator.GetPendingMigrations().Any())
migrator.Update();
}
// DbSet's
public DbSet<CountryRegion> CountryRegion { get; set; }
// bla bla bla.....
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
//Configuration.ValidateOnSaveEnabled = false;
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly()); // Discover and apply all EntityTypeConfiguration<TEntity> of this assembly, it will discover (*)
}
}
internal sealed class DataDbInitializer : MigrateDatabaseToLatestVersion<DataDbContext, DataDbConfiguration>
{
}
internal sealed class DataDbConfiguration : DbMigrationsConfiguration<DataDbContext>
{
public DataDbConfiguration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(DataDbContext context)
{
DataSeedInitializer.Seed(context);
base.Seed(context);
}
}
internal static class DataSeedInitializer
{
public static void Seed(DataDbContext context)
{
SeedCountryRegion.Seed(context);
// bla bla bla.....
context.SaveChanges();
}
}
internal static class SeedCountryRegion
{
public static void Seed(DataDbContext context)
{
context.CountryRegion.AddOrUpdate(countryRegion => countryRegion.Id,
new CountryRegion { Id = "AF", Name = "Afghanistan" },
new CountryRegion { Id = "AL", Name = "Albania" },
// bla bla bla.....
new CountryRegion { Id = "ZW", Name = "Zimbabwe" });
context.SaveChanges();
}
}
public class CountryRegionConfiguration : EntityTypeConfiguration<CountryRegion> // (*) Discovered by
{
public CountryRegionConfiguration()
{
Property(e => e.Id)
.IsRequired()
.HasMaxLength(3);
Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
}
}
public partial class CountryRegion : IEntity<string>
{
// Primary key
public string Id { get; set; }
public string Name { get; set; }
}
public abstract class Entity<T> : IEntity<T>
{
//Primary key
public abstract T Id { get; set; }
}
public interface IEntity<T>
{
T Id { get; set; }
}
We can see that the Seed method is running again and again..
We can avoid this by checking if a migration already exits, since one is applied automatically when the database is create.. then we can refactor the DataDbConfiguration as follows...
internal sealed class DataDbConfiguration : DbMigrationsConfiguration<DataDbContext>
{
private readonly bool _isInitialized;
public DataDbConfiguration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
var migrator = new DbMigrator(this);
_isInitialized = migrator.GetDatabaseMigrations().Any();
}
protected override void Seed(DataDbContext context)
{
InitializeDatabase(context);
}
public void InitializeDatabase(DataDbContext context)
{
if (!_isInitialized)
{
if (context.Database.Connection.ConnectionString.Contains("localdb"))
{
DataSeedInitializer.Seed(context); // Seed Initial Test Data
}
else
{
// Do Seed Initial Production Data here
}
}
else
{
// Do any recurrent Seed here
}
}
}
Here is my current solution, which I'm not completely satisfied with.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
var context = new KCSoccerDataContext();
var initializeDomain = new CreateDatabaseIfNotExists<KCSoccerDataContext>();
var initializeMigrations = new MigrateDatabaseToLatestVersion<KCSoccerDataContext, Core.Migrations.Configuration>();
initializeDomain.InitializeDatabase(context);
initializeMigrations.InitializeDatabase(context);
}
I'm actually creating two different initializers. The first, using CreateDatabaseIfNotExists, succcessfully goes through and creates tables based on my Domain objects. The second, using MigrateDatabaseToLatestVersion, executes all of my explicit migrations.
I don't like it because Automatic Migrations are basically disabled. So in order to add or change my Domain model I have to completely drop the database and recreate it. This won't be acceptable once I've moved the application to production.
If your application contains Startup.cs class, you can use DbMigrator Class as follows
Go to your App_Start folder, open Startup.Auth
Paste these lines of code inside of ConfigureAuth method
var configuration = new Migrations.Configuration();
var dbmigrator = new DbMigrator(configuration);
dbmigrator.Update();
NOTE: Remember to use this namespace- using System.Data.Entity.Migrations;
what this does is to update your database to the latest version anytime the application starts up
You just need to do
private static void InitializeDataStore()
{
System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion<GalleryDb, GalleryDbMigrationConfiguration>());
System.Data.Entity.Database.Initialize(false);
}