【问题标题】:C#: asp.net CORE empty MigrationC#:asp.net CORE 空迁移
【发布时间】:2020-02-20 11:40:50
【问题描述】:

我正在尝试添加来自 DatabaseContext 的迁移 但是当我添加迁移时,我会像这样将其生成为空。我一直在关注这个教程

namespace MovieExampleAppDotNetCore.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class ModelMigration : DbMigration
    {
        public override void Up()
        {
        }

        public override void Down()
        {
        }
    }
}

这些是模型、迁移配置、启动和DatabaseContext

Movie.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace MovieExampleAppDotNetCore.Models
{
    public class Movie
    {   
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int MovieId { get; set; }
        public String Name { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime? DateCreated { get; set; }
    }
}

Customer.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace MovieExampleAppDotNetCore.Models
{
    public class Customer
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CustomerId { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public bool IsCreated { get; set; }
        public int MaxMovies { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime Created { get; set; }

        [Column(TypeName = "datetime2")]
        public DateTime? LastEdited { get; set; }


    }
}

Configuration.cs

namespace MovieExampleAppDotNetCore.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<MovieExampleApp.Persistention.DatabaseContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(MovieExampleApp.Persistention.DatabaseContext context)
        {

        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method
        //  to avoid creating duplicate seed data.
    }
}

}

DatabaseContext.cs

using Microsoft.EntityFrameworkCore;
using MovieExampleAppDotNetCore.Models;
using System.Data.Entity;


namespace MovieExampleApp.Persistention
{
    public class DatabaseContext : System.Data.Entity.DbContext
    {
        public DatabaseContext() : base("main")
        {
            //Database.Initialize(true);
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        public Microsoft.EntityFrameworkCore.DbSet<Movie> Movies { get; set; }
        public Microsoft.EntityFrameworkCore.DbSet<Customer> Customers { get; set; }
    }
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using MovieExampleApp.Persistention;
using System.Linq;

namespace MovieExampleAppDotNetCore
{
    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)
        {

            services.AddDbContext<DatabaseContext>(
                        options => options.UseSqlServer(Configuration.GetConnectionString("DatabaseContext")));

            services.AddControllersWithViews().AddNewtonsoftJson();

            services.AddControllersWithViews(options =>
            {
                options.InputFormatters.Insert(0, GetJsonPatchInputFormatter());
            });

        }

        private static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter()
        {
            var builder = new ServiceCollection()
                .AddLogging()
                .AddMvc()
                .AddNewtonsoftJson()
                .Services.BuildServiceProvider();

            return builder
                .GetRequiredService<IOptions<MvcOptions>>()
                .Value
                .InputFormatters
                .OfType<NewtonsoftJsonPatchInputFormatter>()
                .First();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

我希望有人能告诉我我做错了什么。

【问题讨论】:

  • 如果它正在生成一个空迁移,那么您的数据库可能已经被标记为具有当前迁移。检查数据库中的迁移表,确认最新迁移是否与上述迁移不同。
  • 我目前在 Server Management Studio 中没有表。所以这不是问题。
  • 有没有桌子都没有关系。如果您之前创建了迁移然后删除了数据库,则之前的迁移(和快照仍然存在于您的迁移文件文件夹中。EF Core 将您当前的模型与您的 DatabaseContextModelSnapshot.cs 匹配。仅当您的当前模型和您的迁移具有任何值的上一个快照
  • 我删除了迁移文件夹更新的数据库并启用了迁移。但是当我添加迁移时,它仍然是空的。
  • 如果您已经完成了上述操作,那么您的数据库已经是最新的了。对模型进行更改后,将触发带有更改的迁移。尝试将属性添加到您的客户实体并尝试另一次迁移,您应该会在 Up 中看到添加的属性,而在 Down 中将其删除。

标签: c# asp.net-core ef-code-first entity-framework-migrations


【解决方案1】:

我找到了我的问题的答案。 我正在使用using System.Data.Entity; 而不是using Microsoft.EntityFrameworkCore;

这是工作代码

DatabaseContext.cs

using Microsoft.EntityFrameworkCore;
using MovieExampleAppDotNetCore.Models;


namespace MovieExampleApp.Persistention
{
    public class DatabaseContext : DbContext
    {
        public DatabaseContext(DbContextOptions<DatabaseContext> context) : base(context)
        {
            //Database.Initialize(true);
        }

        public DatabaseContext()
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Movie> Movies { get; set; }
        public DbSet<Customer> Customers { get; set; }
    }
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore.SqlServer;
using System.Linq;
using MovieExampleApp.Persistention;

namespace MovieExampleAppDotNetCore
{
    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)
        {
            services.AddMvc();
            services.AddDbContext<DatabaseContext>(
            options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


            services.AddControllersWithViews().AddNewtonsoftJson();

            services.AddControllersWithViews(options =>
            {
                options.InputFormatters.Insert(0, GetJsonPatchInputFormatter());
            });

        }

        private static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter()
        {
            var builder = new ServiceCollection()
                .AddLogging()
                .AddMvc()
                .AddNewtonsoftJson()
                .Services.BuildServiceProvider();

            return builder
                .GetRequiredService<IOptions<MvcOptions>>()
                .Value
                .InputFormatters
                .OfType<NewtonsoftJsonPatchInputFormatter>()
                .First();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

【讨论】:

    【解决方案2】:

    据我所知,您不需要像使用 [Key] 一样使用 [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - 这足以在属性上设置主键。

    试试这个方法:

    首先我会通过输入 Package-Manger-Console 来删除空迁移:

    移除迁移

    我还假设您没有任何其他迁移,您实际上已经添加了您现在想要添加的这些模型。

    然后:

    ApplicationDbContext Class:

    public class ApplicationDbContext : DbContext
    {
                public ApplicationDbContext(DbContextOptions<ApplicationDbContext> context) : base(context)
        {
        }
    
        public DbSet<Movie> Movies { get; set; }
        public DbSet<Customer> Customers { get; set; }
    }
    

    我假设您在启动时获得了更新数据库的所有内容,但只是提一下:

    Startup:

        public void ConfigureServices(IServiceCollection services)
        {
    
         //some code...
                services.AddDbContext<ApplicationDbContext>(
                options => options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
        }
    

    当然还要更新 appsettings.json 中的连接字符串以反映连接名称:

      "ConnectionStrings": {
    "DevConnection": "Server=SERVER; Database=DB; Trusted_Connection=True; MultipleActiveResultSets=True;",
    
     }
    

    然后输入 Package-Manager-Console:add-migration [Migration Name]

    【讨论】:

    • 我想我找到了问题所在。当我尝试添加 services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DatabaseContext")));它没有看到我的 dbcontext。
    • 您的数据库上下文类是:DatabaseContext 而在 Startup 中您将其命名为:ApplicationDatabaseContext。
    • 对不起,我再次编辑它们都是相同的名称,但错误仍然存​​在。
    • 好吧,今天早上我试了一下,它成功了,但是当我删除迁移时,它又开始进行空迁移,这真的很奇怪,因为我没有改变任何东西,现在它仍然坏了。跨度>
    • 您的迁移文件夹完全为空吗?但是,如果您进行了迁移并更新了数据库,它将不会添加另一个迁移,因为模型已经存在!如果您想清除数据库,您可以从 SQL Server Management Studio 执行此操作,也可以在 ApplicationDbContext Class 和 add-migration 中注释掉您的类。它应该创建迁移,其中将有“Drop Table Movies”等。
    【解决方案3】:

    使用这个;添加迁移迁移1 在调用更新数据库之前

    【讨论】:

    • 这无济于事,它会再次创建空迁移。他的解决方案是致电update-database 或正确检查 DbContext 和模型。
    猜你喜欢
    • 1970-01-01
    • 2021-11-22
    • 2021-06-04
    • 2017-08-27
    • 2017-03-31
    • 2019-03-06
    • 2016-06-30
    • 1970-01-01
    • 2020-01-29
    相关资源
    最近更新 更多