如何向 EntityFramework 7 项目添加迁移

How add a migration to a EntityFramework 7 project

我正在使用 asp.net 5 和 EF 7 VS2015 开始一个新项目。

我选择了带有用户管理的项目模板。 现在我想向 dbContext 添加一些 类 并使用我的新 类.

创建一个新模式

这是我的 ApplicationDbContext 的样子:

    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);
    }
}

我无法重新创建我的数据库或将我的数据库迁移到我的 CandidatesManagers table.

的版本

我必须输入哪些命令才能显示我的数据库?我的朋友 Google 和 Bing 为我指出了各个方向,但我发现 none 的方法有效。

您需要使用新的 dnx 命令,例如:

dnx . ef migration add NameOfMigration

并向 运行 迁移:

dnx . ef migration apply

我发现这个 CodeProject article 显示了如何处理 ASP .NET 5 项目上的迁移,但总而言之,您需要应用@DavidG 在他的回答中推荐的命令。

我知道这不是你的情况,但如果你正在使用 Class 库 项目,那么你需要 运行这些是:

打开包管理器控制台

  • 运行 Add-Migration MigrationName 如果是第一次,它将构建一个迁移来为你的模型创建初始的一组表,否则它将构建下一个基于自上次创建迁移以来您对模型所做的更改的迁移。

  • 运行 Apply-Migration 将新迁移应用到数据库。 如果您的数据库尚不存在,将为您创建 在应用迁移之前。

要应用这些命令,您需要先配置数据库提供程序。您可以通过在 DbContext class 或 AddDbContext 方法中重写 OnConfiguring 来实现此目的。

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {          
     optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp;Trusted_Connection=True;");
 }

根据 ASP.NET 5 和实体 7 RC1,步骤为:

  1. 在您的主项目中添加对 Entity Commands nuget 包的依赖。所以在你的 project.json 你应该看到这种依赖 "EntityFramework.Commands": "7.0.0-rc1-final"
  2. 添加一个别名命令以便稍后从控制台使用。因此,在您的 project.json 中,您将拥有以下 ef 命令: "commands": { "ef": "EntityFramework.Commands", "web": "Microsoft.AspNet.Server.Kestrel" }
  3. 打开控制台并运行迁移命令。例如:

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

  4. 然后查看 ef 将在您的项目中创建的迁移,并使用以下命令将更改应用到您的数据库(为您的项目配置的数据库):

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

请注意,属性 --targetProject 允许您指定 DbContext 所在的项目以及将创建文件夹 Migrations 的位置。如果您的 DbContext 在您的主项目中,您可以忽略它(但我建议为所有与持久性相关的内容创建一个 class 库项目,这样这个命令会很方便)

在您的 Startup.cs 中,您通常会配置实体,包括连接字符串。这是一个基本示例:

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);
}