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);
}
}
}
Related
I have a project that uses Microsoft.EntityFrameworkCore.Sqlite 6.0.5 on net6.0. I am expecting the Sqlite database file to be unlocked after the DbContext has been disposed.
However, the behaviour I am observing is that the Sqlite database remains locked after the DbContext has been disposed and finalised. There is a project that reproduces the behaviour here.
How can I unlock the database file?
My DbContext looks like this:
public class MyContext : DbContext
{
~MyContext()
{
Console.WriteLine("Finaliser was called.");
}
public override void Dispose()
{
base.Dispose();
Console.WriteLine("Dispose was called.");
}
public static readonly string DbFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "_temp.db");
public DbSet<Foo> Summaries { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Foo>().HasKey(nameof(Foo.Id));
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlite($"Data Source={DbFile}");
}
}
I am using it like this:
public static void AddItem()
{
using var ctx = new MyContext();
ctx.Database.EnsureCreated();
ctx.Summaries.Add(new Foo {Bar = "Foo"});
ctx.SaveChanges();
}
ClearAllPools() or specify no pooling in connection string (Pooling=false)
https://learn.microsoft.com/en-us/dotnet/standard/data/sqlite/connection-strings#pooling
Trying to learn EF Core, have just finished a course online and I am trying to get an integer added to a DB table. .Net 5.0.
I am getting an error when I build the application:
'AddDbContext' was called with configuration, but the context type 'ApplicationDbContext' only declares a parameterless constructor. This means that the configuration passed to 'AddDbContext' will never be used. If configuration is passed to 'AddDbContext', then 'ApplicationDbContext' should declare a constructor that accepts a DbContextOptions and must pass it to the base constructor for DbContext.
Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.CheckContextConstructors()
I understand the problem is between ApplicationDBContext.cs and Startup.cs, one has parameters and one is parameterless, but I don't know how to fix it. Other answers online seem to be along the lines of "This is obvious, just fix it" which is not very helpful.
ApplicationDBContext
If I un-comment the empty ApplicationDbContext functions I no longer get the error, but when I run the program nothing is added to my DB.
using System;
using System.Collections.Generic;
using System.Text;
using MyApp.Areas.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace MyApp.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<RGWAction> RGWActions { get; set; }
DBConnectionStringFactory GetDBConnectionString = new DBConnectionStringFactory();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string ConnectionString = GetDBConnectionString.DBConnectionString();
optionsBuilder.UseSqlServer(ConnectionString).LogTo(Console.WriteLine, new[] { DbLoggerCategory.Database.Command.Name },LogLevel.Information)
.EnableSensitiveDataLogging(); //add to be able to see parameters in your log
}
/*
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public ApplicationDbContext()
{
}
*/
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services) method
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
RGWAction.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace MyApp.Areas.Identity
{
public class RGWAction
{
public int Id { get; set; }
public string Email { get; set; }
public int Total { get; set; }
public int ReduceMeat { get; set; }
}
}
Program.cs
Just trying to add an integer to the DB on startup right now, to get it working as a learning exercise. My next step will be to trigger it from a UI button.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MyApp.Data;
using MyApp.Areas.Identity;
namespace MyApp
{
public class Program
{
private static ApplicationDbContext _context = new ApplicationDbContext();
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
InsertNewInteger();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
private static void InsertNewInteger()
{
_context.RGWActions.Add(new RGWAction { ReduceMeat = 1 });
_context.SaveChanges();
}
}
}
DB Table:
Advice would be much appreciated.
You need an ApplicationDbContext constructor with a DbContextOptions parameter to insert option dependencies.
You need a default constructor without parameters because you call it explicitly in the _context field initializer. Try to omit this initialization, it is unnecessary if DI works well.
Your controller:
public class YourController : Controller
{
[HttpPost] // because data is updated
public async Task<ActionResult> NewIntAction(
[FromServices]
INewIntService newIntService)
{
await newIntService.InsertNewInteger();
....
return View(); // You will need a view NewIntAction in the folder Views/Your
}
}
INewIntService interface :
public interface INewIntService
{
Task InsertNewInteger();
}
NewIntService class:
public sealed class NewIntService : INewIntService
{
public NewIntService(ApplicationDbContext context)
{
_context = context;
}
ApplicationDbContext _context;
public async Task InsertNewInteger()
{
_context.RGWActions.Add(new RGWAction { ReduceMeat = 1 });
await _context.SaveChangesAsync();
}
}
Startup.cs:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<INewIntService, NewIntService>();
Main program:
namespace MyApp
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
InsertNewInteger();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
I need define no constructor of ApplicationDbContext because the instance of ApplicationDbContext is created by the infrastructure and injected as a dependency into the NewIntService constructor in its context parameter.
Ahhhh, finally! :)
ApplicationDBContext needs all three methods. Does anyone know why?
OnConfiguring(DbContextOptionsBuilder optionsBuilder)
ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
ApplicationDbContext()
Also Program.cs was the wrong place for my InsertNewInteger() method. It needed to be in the controller for the page load, in this case index.cs controller.
build a web api using entityframeworkcore 2.03 .net core
keep getting the following error tried everything i can think of to get past it not sure what the issue is has anyone else had this iasue ?
InvalidOperationException: No database provider has been configured
for this DbContext. A provider can be configured by overriding the
DbContext.OnConfiguring method or by using AddDbContext on the
application service provider. If AddDbContext is used, then also
ensure that your DbContext type accepts a DbContextOptions
object in its constructor and passes it to the base constructor for
DbContext
startup.cs
using churchy.Repository;
using churchy.Service;
using churchy.Service.Abstractions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace churchy
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Database connection
services.AddDbContext<ChurchContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ChurchConnection")));
// Repositories
services.AddScoped<IRepository, Repository.Repository>();
services.AddScoped<IRepositoryFactory, RepositoryFactory>();
// Services
services.AddScoped<IChurchService, ChurchService>();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
churchcontext.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using churchy.Model;
namespace churchy.Repository
{
public class ChurchContext: DbContext
{
public ChurchContext()
{
}
public ChurchContext(DbContextOptions<ChurchContext> options) : base(options)
{
}
public DbSet<Church> Churches { get; set; }
public DbSet<Location> Locations { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Church>().ToTable("Church");
}
}
}
Repository.cs
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;
namespace churchy.Repository
{
public class Repository : IRepository
{
private readonly ChurchContext _context;
public Repository()
{
_context = new ChurchContext();
}
public IQueryable<T> GetAll<T>() where T : class
{
return _context.Set<T>();
}
public Task Create<T>(T entity) where T : class
{
throw new System.NotImplementedException();
}
public Task Delete<T>(int id) where T : class
{
throw new System.NotImplementedException();
}
public Task Update<T>(int id, T entity) where T : class
{
throw new System.NotImplementedException();
}
public void Dispose()
{
_context?.Dispose();
}
}
}
IRepository.cs
using System;
using System.Linq;
using System.Threading.Tasks;
namespace churchy.Repository
{
public interface IRepository : IDisposable
{
IQueryable<T> GetAll<T>() where T : class;
Task Create<T>(T entity) where T :class;
Task Update<T>(int id, T entity) where T : class;
Task Delete<T>(int id) where T : class;
}
}
ChurchController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using churchy.Service.Abstractions;
namespace churchy.Controllers
{
[Route("api/church")]
public class ChurchController : Controller
{
private readonly IChurchService _churchService;
public ChurchController(IChurchService churchService)
{
_churchService = churchService;
}
// GET: api/<controller>
[HttpGet]
public IActionResult GetAllAsync()
{
var response = _churchService.getChurches();
return Ok(response);
}
// GET api/<controller>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value3";
}
// POST api/<controller>
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
Here is your most fundamental problem:
public Repository()
{
_context = new ChurchContext();
}
That's the opposite of Dependency Injection. That context you are manually creating has not been configured.
Quick answer:
public Repository(ChurchContext context)
{
_context = context;
}
Furthermore:
You should get familiar with Dependency Injection in ASP.NET Core: Dependency Injection in ASP.NET Core.
You may want to read this answer of mine for some viewpoints regarding UoW and Repository patterns in ASP.NET Core.
I'm updating a webform app to a mvc app but I have an issue.
I would like to create automatically the AspNetUsers tables when I try, for the first time,to log in through the webApp
Below the error messages:
The target context 'PROJECT.Data.DataContext' is not constructible.
Add a default constructor or provide an implementation of
IDbContextFactory.
Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for
databases created using Code First or Code First Migrations.
The first one is fired with the code below:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, MyConfiguration>());
public class MyConfiguration : DbMigrationsConfiguration<DataContext>
{
public MyConfiguration()
{
this.AutomaticMigrationsEnabled = true;
}
protected override void Seed(DataContext context)
{
InitializeIdentityForEF(context);
base.Seed(context);
}
public void InitializeIdentityForEF(DataContext db)
{
// create admin user with role and claims
}
}
The second one:
Database.SetInitializer(new ApplicationDbInitializer());
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<DataContext>
{
protected override void Seed(DataContext context)
{
InitializeIdentityForEF(context);
base.Seed(context);
}
public void InitializeIdentityForEF(DataContext db)
{
// create admin user with role and claims
}
}
I think that I can fix this issue if I enable the the migration through the console but I would like to implement everything in the code. Any idea to mix theses two code above?
NOTE: I just want to create the AspNetUser table because I'm using "Database First" once they are created.
public class DataContext : DbContext, IEntitiesContext
{
private static readonly object Lock = new object();
private static bool _databaseInitialized;
public DataContext(string nameOrConnectionString, ILogger logger) : base(nameOrConnectionString)
{
Database.Log = logger.Log;
if (_databaseInitialized)
{
return;
}
lock (Lock)
{
if (!_databaseInitialized)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, MyConfiguration>());
Database.SetInitializer(new ApplicationDbInitializer());
_databaseInitialized = true;
}
}
}
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);
}