如何將遷移添加到EntityFramework 7項目


我正在使用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表的版本。

我必須輸入哪些命令才能顯示數據庫?我的朋友谷歌和必應向我指出了各個方向,但我找不到任何有用的東西。

一般承認的答案

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

dnx . ef migration add NameOfMigration

並運行遷移:

dnx . ef migration add NameOfMigration

熱門答案

根據ASP.NET 5和Entity 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所在的項目以及將創建文件夾遷移的位置。如果您的DbContext在您的主項目中,您可以省略(但我建議有一個類庫項目,所有持久性相關,所以這個命令會很方便)

在您的Startup.cs中,您通常會擁有Entity的配置,包括連接字符串。這是一個基本的例子:

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




許可下: CC-BY-SA
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因