How add a migration to a EntityFramework 7 project

asp.net-core code-first-migrations entity-framework entity-framework-core

Question

I'm starting a new project using asp.net 5 and EF 7 VS2015.

I selected the project template with the user mangagement. Now I want to add some classes to the dbContext and have a new schema created with my new classes.

This is wat my ApplicationDbContext looks like:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Candidate> Candidates { get; set; }
    public DbSet<Manager> Managers { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
        builder.Entity<Candidate>().Key(x => x.Id);
        builder.Entity<Manager>().Key(x => x.Id);
    }
}

I have not been able to recreate or migrate my database to a version with my Candidates and Managers table.

Which commands do I have to enter where to make my DB appear? My friend Google and Bing have pointed me in every direction, but none of the things I found worked.

Accepted Answer

You need to use the new dnx commands, for example:

dnx . ef migration add NameOfMigration

And to run the migration:

dnx . ef migration apply

Popular Answer

As per ASP.NET 5 and Entity 7 RC1 the steps would be:

  1. Add a dependency to the Entity Commands nuget package in your main project. So in your project.json you should see this dependency "EntityFramework.Commands": "7.0.0-rc1-final"
  2. Add an alias command to use from console later on. So in your project.json you would have the following ef command: "commands": { "ef": "EntityFramework.Commands", "web": "Microsoft.AspNet.Server.Kestrel" }
  3. Open a console and run the migration commands. For example:

    D:\Projects\MyProject\src\MyProject.Web.Api>dnx ef migrations add Initial --targetProject MyProject.Data.SqlServer

  4. Then review the Migration that ef will create in your project and apply the changes to your database (the database that is configured for your project) with the following command:

    D:\Projects\MyProject\src\MyProject.Web.Api>dnx ef database update

Notice that the attribute --targetProject allows you to specify the project where your DbContext is and where the folder Migrations would be created. If your DbContext is in your main project you can omit that (but I recommend to have a class library project for everything persistance related so this command would be handy)

In your Startup.cs is where you usually would have the configuration for Entity including the connection string. This is a basic example:

public Startup(IHostingEnvironment env)
    {
        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; private set; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<KuneDbContext>(options => {
                options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);
            });

        // Add identity here http://docs.asp.net/en/latest/tutorials/your-first-aspnet-application.html

        services.AddMvc();

        // Add application services
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");

            // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
            try
            {
                using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                    .CreateScope())
                {
                    serviceScope.ServiceProvider.GetService<KuneDbContext>()
                         .Database.Migrate();
                }
            }
            catch { }
        }

        app.UseIISPlatformHandler();

        app.UseStaticFiles();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        //Seed Data if you want to load some test data in the DB
        //SeedData.Initialize(app.ApplicationServices);
    }

    // Entry point for the application.
    public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why