从.net core 1.x更新到2.x后无法运行mysql数据库迁移,未知数据库“”

zpqajqem  于 2021-06-20  发布在  Mysql
关注(0)|答案(0)|浏览(289)

我最近尝试使用mysql将一个正在工作的.NETCore1.0项目更新为.NETCore2.0。我按照microsoft文档中的说明进行了编译和运行,但我完全无法执行数据库迁移。每当我尝试从包管理器控制台运行update database时,我都会出现一个错误,错误是:

One or more errors occurred. (Authentication to host 'localhost' for user 'user' using method 'mysql_native_password' failed with message: Unknown database '')

我的问题是,即使用户名和连接正确地取自连接字符串,数据库名称却不是。我甚至使用连接字符串中的相同信息从服务器资源管理器窗口连接到数据库;我检查了正确的appsettings(开发)文件是否在使用中。

"ConnectionStrings": {
    "DefaultConnection": "server=localhost;database=asm;userid=user;password=password;connectionreset=true;Allow User Variables=True"
  },

我在google上搜索了错误消息,但只找到了数据库名称有拼写错误或明显不存在的帖子和评论,但事实并非如此。数据库用户拥有mysql workbench中设置的所有管理角色和权限。任何帮助或指针(甚至如何调试update数据库进程,以便在创建/设置dbcontext时进行检查)都将不胜感激。
添加信息:
startup.cs(经过修订,省略了一些using和大多数服务。addscoped<>())

using asm.Data;
using asm.Enumeration;
using asm.Models;
using asm.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Localization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.AspNetCore.DataProtection;
using System.IO;
using System.Threading.Tasks;
using MySql.Data.EntityFrameworkCore.Extensions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Serilog;

namespace asm
{
    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.AddLocalization(options => options.ResourcesPath = "Resources");

            // Add Options
            services.AddOptions();

            services.Configure<Options>(Configuration.GetSection("Properties"));

            services.AddDataProtection()
                .PersistKeysToFileSystem(new DirectoryInfo("/opt/app/key/"))
                .SetDefaultKeyLifetime(TimeSpan.FromDays(90));

            //Add MVC properties
            services.AddMvc()
                .AddViewLocalization()
                .AddDataAnnotationsLocalization();
            services.AddScoped<ILanguageActionFilter, LanguageActionFilter>();
            services.Configure<RequestLocalizationOptions>(
                options =>
                {
                    var supportedCultures = new List<CultureInfo>
                    {
                        new CultureInfo("es-AR"),
                        new CultureInfo("es"),
                        new CultureInfo("en-US"),
                        new CultureInfo("en")
                    };
                    options.DefaultRequestCulture = new RequestCulture(culture: "es-AR", uiCulture: "es-AR");
                    options.SupportedCultures = supportedCultures;
                    options.SupportedUICultures = supportedCultures;
                });

            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseMySQL(Configuration.GetConnectionString("DefaultConnection"),
                b => b.MigrationsAssembly("asm"))
            );

            services.AddSingleton<Microsoft.AspNetCore.Identity.IdentityErrorDescriber, Services.Security.IdentityErrorDescriber>();

            services.AddIdentity<ApplicationUser, Role>((opt) =>
            {
                opt.Password.RequireDigit = true;
                opt.Password.RequireLowercase = true;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase = true;
                opt.Password.RequiredLength = 6;
            })
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            //Add Memory Cache
            services.AddMemoryCache();

            services.AddDistributedMemoryCache();

            services.AddSession(options => { options.CookieName = ".cookie.name"; options.IdleTimeout = TimeSpan.FromMinutes(40); });

            // Security
            services.AddAuthorization(options =>
            {
                options.AddPolicy("User Register", policy => policy.RequireClaim("UserRegister"));
                options.AddPolicy("Portal Policy", policy => policy.RequireClaim("PortalClaim"));
            });

            #region GlobalIsoDependencies

            // Redacted: Lots of services like: 
            // services.AddScoped<ThingRepository, ThingRepository>();

        }

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

            loggerFactory.AddDebug();

            loggerFactory.AddSerilog();

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

            app.UseStaticFiles();

            var options = app.ApplicationServices.GetService<Microsoft.Extensions.Options.IOptions<RequestLocalizationOptions>>();
            app.UseRequestLocalization(options.Value);

            app.UseAuthentication();

            app.UseSession();

            // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

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

        }

    }
}

applicationdbcontext.cs(也经过修订):

using System;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using crm.Models;
using crm.Models.GlobalIso;
using crm.Models.EmailMarketing;
using crm.Models.Idomum;
using crm.Models.Integrations.Mercadopago;
using crm.Models.GlobalIso.MA;
using crm.Models.GlobalIso.Type;
using crm.Models.GlobalIso.RT;
using crm.Models.GlobalIso.Maintenance;
using crm.Models.Crm;

namespace asm.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Role, string>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            // Redacted: Lots of:
            // builder.Entity<>(ClassName).ToTable("TABLE_NAME");

            builder.Entity<Profile>().ToTable("ROLE_PROFILE");
            builder.Entity<UserProfile>().ToTable("ROLE_PROFILE_USER");
            builder.Entity<ProfileRole>().ToTable("ROLE_PROFILE_ROLE");

            String longtext = "LONGTEXT";

            builder.Entity<ApplicationUser>()
                .HasMany(e => e.Claims)
                .WithOne()
                .HasForeignKey(e => e.UserId)
                .IsRequired()
                .OnDelete(DeleteBehavior.Cascade);

            builder.Entity<ApplicationUser>()
                .HasMany(e => e.Logins)
                .WithOne()
                .HasForeignKey(e => e.UserId)
                .IsRequired()
                .OnDelete(DeleteBehavior.Cascade);

            builder.Entity<ApplicationUser>()
                .HasMany(e => e.Roles)
                .WithOne()
                .HasForeignKey(e => e.UserId)
                .IsRequired()
                .OnDelete(DeleteBehavior.Cascade);

            builder.Entity<ApplicationUser>()
            .HasOne(p => p.Enterprise)
            .WithMany(e => e.ApplicationUserList);

            builder.Entity<Role>()
            .HasOne(p => p.Application);

            builder.Entity<UserProfile>()
                .HasKey(up => new { up.ApplicationUserID, up.ProfileID });

            builder.Entity<UserProfile>()
                .HasOne(up => up.ApplicationUser)
                .WithMany(u => u.UserProfileList)
                .HasForeignKey(up => up.ApplicationUserID);

            builder.Entity<UserProfile>()
                .HasOne(up => up.Profile)
                .WithMany(p => p.UserProfileList)
                .HasForeignKey(up => up.ProfileID);

            builder.Entity<ProfileRole>()
                .HasKey(pr => new { pr.RoleID, pr.ProfileID });

            //TODO: The key {'RoleID'} contains properties in shadow state and is referenced by a relationship from 'Role.PerfileRoleList' to 'PerfileRole.Role'.
            //Configure a non-shadow principal key for this relationship.
            builder.Entity<ProfileRole>()
                .HasOne(pr => pr.Role)
                .WithMany(r => r.ProfileRoleList)
                .HasForeignKey(pr => pr.RoleID);

            builder.Entity<ProfileRole>()
                .HasOne(pr => pr.Profile)
                .WithMany(p => p.ProfileRoleList)
                .HasForeignKey(pr => pr.ProfileID);

            builder.Entity<Enterprise>()
                .HasOne(tc => tc.Enterprise_Parent)
                .WithMany(p => p.EnterpriseChildList)
                .HasForeignKey(tc => tc.Enterprise_ParentID);

            builder.Entity<UserEnterprise>()
                .HasKey(t => new { t.ApplicationUserID, t.EnterpriseID });

            builder.Entity<UserEnterprise>()
                .HasOne(ue => ue.ApplicationUser)
                .WithMany(p => p.UserEnterpriseList)
                .HasForeignKey(tc => tc.ApplicationUserID);

            builder.Entity<UserEnterprise>()
                .HasOne(ue => ue.Enterprise)
                .WithMany(p => p.UserEnterpriseList)
                .HasForeignKey(tc => tc.EnterpriseID);
        }

        public DbSet<Enterprise> Enterprise { get; set; }
        public DbSet<UserEnterprise> UserEnterprise { get; set; }
        public DbSet<ApplicationUser> ApplicationUser { get; set; }

        public DbSet<Application> Application { get; set; }

        public DbSet<ApplicationEnterprise> ApplicationEnterprise { get; set; }

        // Many to Many Relations
        public DbSet<UserSettings> UserSettings { get; set; }

        public DbSet<Profile> Profile { get; set; }
        public DbSet<ProfileRole> ProfileRole { get; set; }
        public DbSet<UserProfile> UserProfile { get; set; }

    }
}

程序.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using asm.Models;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace asm
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    SeedData.Initialize(services).Wait();
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred seeding the DB.");
                }

            }
            host.Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();

    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题