知道为啥我的 DbInitializer 中的数据没有填充到我的数据库中

Posted

技术标签:

【中文标题】知道为啥我的 DbInitializer 中的数据没有填充到我的数据库中【英文标题】:Any idea why the data in my DbInitializer is not populating in my database知道为什么我的 DbInitializer 中的数据没有填充到我的数据库中 【发布时间】:2021-12-20 18:04:56 【问题描述】:

使用 SQL Server Express LocalDB,我在 DbInitializer 中编码的数据不会填充到我的数据库中。我不确定是延迟加载还是缺少某些内容导致数据无法播种。

ApplicationDbContext.cs

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using FinesJune.Models;

namespace FinesJune.Data

    public class ApplicationDbContext : IdentityDbContext
    
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        
        

        // The Fines table
        public DbSet<Fine> Fines  get; set; 

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

这是我的DbInitializer 课程,其中数据被写入以在播种时编码到数据库中:

using FinesJune.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;

namespace FinesJune.Data

    public static class DbInitializer
    
        public static void Seed(ApplicationDbContext context, IServiceProvider services)
        
            // Seed roles
            // Get the Identity Role Manager from services
            RoleManager<IdentityRole> roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
            // Create each role
            roleManager.CreateAsync(new IdentityRole()  Name = "Traffic Manager" ).Wait();
            roleManager.CreateAsync(new IdentityRole()  Name = "Traffic Officer" ).Wait();
            roleManager.CreateAsync(new IdentityRole()  Name = "Driver" ).Wait();

            // Add the test users (one for each role). Employs the usermanager service.
            // Driver test user
            UserManager<IdentityUser> userManager = services.GetRequiredService<UserManager<IdentityUser>>();
            userManager.CreateAsync(new IdentityUser()
            
                Email = "driver@testwebsite.com",
                UserName = "driver@testwebsite.com",
                EmailConfirmed = true,
                TwoFactorEnabled = false
            ).Wait();
            // Get the user from the DB
            IdentityUser driverUser = userManager.Users.FirstOrDefault(c => c.Email == "driver@testwebsite.com");
            // Give it a password and the appropriate role
            userManager.AddPasswordAsync(driverUser, "Pa$$word1").Wait();
            userManager.AddToRoleAsync(driverUser, "Driver").Wait();

            // Officer test user
            userManager.CreateAsync(new IdentityUser()
            
                Email = "officer@testwebsite.com",
                UserName = "officer@testwebsite.com",
                EmailConfirmed = true,
                TwoFactorEnabled = false
            ).Wait();
            // Get the user from the DB
            IdentityUser officerUser = userManager.Users.FirstOrDefault(c => c.Email == "officer@testwebsite.com");
            // Give it a password and the appropriate role
            userManager.AddPasswordAsync(officerUser, "Pa$$word1").Wait();
            userManager.AddToRoleAsync(officerUser, "Traffic Officer").Wait();

            // Manager test user
            userManager.CreateAsync(new IdentityUser()
            
                Email = "manager@testwebsite.com",
                UserName = "manager@testwebsite.com",
                EmailConfirmed = true,
                TwoFactorEnabled = false
            ).Wait();
            // Get the user from the DB
            IdentityUser managerUser = userManager.Users.FirstOrDefault(c => c.Email == "manager@testwebsite.com");
            // Give it a password and the appropriate role
            userManager.AddPasswordAsync(managerUser, "Pa$$word1").Wait();
            userManager.AddToRoleAsync(managerUser, "Traffic Manager").Wait();

            // Seed fines
            var fine = new Fine[]
            
                new Fine 
                    FineID = Guid.NewGuid().ToString(),
                    OfficerID = Guid.NewGuid().ToString(),
                    DriverID = Guid.NewGuid().ToString(),
                    LicensePlate = "CY4345",
                    VehicleType = VehicleType.Car,
                    Offense = OffenseType.Speeding,
                    OffenseDetail = "85km/h in a 60 zone.",
                    OffenseDate = DateTime.Parse("2017-08-10"),
                    OffenseTime = DateTime.Parse("05:50"),
                    Amount = 50.50m,
                    Outstanding = true
                ,
                new Fine 
                    FineID = Guid.NewGuid().ToString(),
                    OfficerID = Guid.NewGuid().ToString(),
                    DriverID = Guid.NewGuid().ToString(),
                    LicensePlate = "CA323566",
                    VehicleType = VehicleType.Bus,
                    Offense = OffenseType.Parking,
                    OffenseDetail = "Parked on red line.",
                    OffenseDate = DateTime.Parse("2018-01-20"),
                    OffenseTime = DateTime.Parse("16:20"),
                    Amount = 350.00m,
                    Outstanding = true
                ,
                new Fine 
                    FineID = Guid.NewGuid().ToString(),
                    OfficerID = Guid.NewGuid().ToString(),
                    DriverID = Guid.NewGuid().ToString(),
                    LicensePlate = "CY198450",
                    VehicleType = VehicleType.Car,
                    Offense = OffenseType.Speeding,
                    OffenseDetail = "140km/h in a 100 zone.",
                    OffenseDate = DateTime.Parse("2014-03-12"),
                    OffenseTime = DateTime.Parse("09:15"),
                    Amount = 500.00m,
                    Outstanding = true
                ,
                new Fine 
                    FineID = Guid.NewGuid().ToString(),
                    OfficerID = Guid.NewGuid().ToString(),
                    DriverID = Guid.NewGuid().ToString(),
                    LicensePlate = "CA321",
                    VehicleType = VehicleType.Motorcycle,
                    Offense = OffenseType.Speeding,
                    OffenseDetail = "65km/h in a 40 zone.",
                    OffenseDate = DateTime.Parse("2018-10-19"),
                    OffenseTime = DateTime.Parse("15:00"),
                    Amount = 250.00m,
                    Outstanding = true
                ,
                new Fine 
                    FineID = Guid.NewGuid().ToString(),
                    OfficerID = Guid.NewGuid().ToString(),
                    DriverID = Guid.NewGuid().ToString(),
                    LicensePlate = "CA974039",
                    VehicleType = VehicleType.Car,
                    Offense = OffenseType.DUI,
                    OffenseDetail = "DUI of alcohol.",
                    OffenseDate = DateTime.Parse("2016-11-11"),
                    OffenseTime = DateTime.Parse("10:10"),
                    Amount = 650.80m,
                    Outstanding = false
                ,
                new Fine 
                    FineID = Guid.NewGuid().ToString(),
                    OfficerID = Guid.NewGuid().ToString(),
                    DriverID = Guid.NewGuid().ToString(),
                    LicensePlate = "CY936503",
                    VehicleType = VehicleType.Car,
                    Offense = OffenseType.Parking,
                    OffenseDetail = "Illegally parked on corner.",
                    OffenseDate = DateTime.Parse("2015-06-21"),
                    OffenseTime = DateTime.Parse("11:41"),
                    Amount = 250.00m,
                    Outstanding = true
                ,
                new Fine 
                    FineID = Guid.NewGuid().ToString(),
                    OfficerID = Guid.NewGuid().ToString(),
                    DriverID = Guid.NewGuid().ToString(),
                    LicensePlate = "CA99840",
                    VehicleType = VehicleType.Truck,
                    Offense = OffenseType.Speeding,
                    OffenseDetail = "100km/h in a 60 zone.",
                    OffenseDate = DateTime.Parse("2016-06-21"),
                    OffenseTime = DateTime.Parse("09:55"),
                    Amount = 1500.00m,
                    Outstanding = true
                ,
            ;
            // Add fines into the in-memory context, then save that context's changes into the DB
            foreach (Fine f in fine)
            
                context.Fines.Add(f);
            
            context.SaveChanges();
        
    

Program.cs

using FinesJune.Data;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FinesJune

    public class Program
    
        public static void Main(string[] args)
        
            var host = CreateHostBuilder(args).Build();

            // Set the service scope
            var services = host.Services.CreateScope().ServiceProvider;

            /* Will run if the context has not yet been created, meaning data is seeded only once.
             * Add an '!' to the boolean of this if statement to force a rerun. */
            if (services.GetRequiredService<ApplicationDbContext>()
                .Database.EnsureCreated())
            
                CreateDbIfNotExists(host);
            

            // Run the host...
            host.Run();
        
        private static void CreateDbIfNotExists(IHost host)
        
            using (var scope = host.Services.CreateScope())
            
                var services = scope.ServiceProvider;

                try
                
                    // Get the context and send it into the DB seed method
                    var context = services.GetRequiredService<ApplicationDbContext>();
                    DbInitializer.Seed(context, services);
                
                catch (Exception ex)
                
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred creating the DB.");
                
            
        

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                
                    webBuilder.UseStartup<Startup>();
                );
    

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FinesJune.Data;


namespace FinesJune

    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<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDatabaseDeveloperPageExceptionFilter();

            // Note that the .AddRoles<IdentityRole>() method is used here to ensure the rolemanager is available in services.
            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddControllersWithViews();
        

        // 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();
                app.UseMigrationsEndPoint();
            
            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.UseAuthentication();
            app.UseAuthorization();

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

我已尝试重新构建、重新启动和运行 Web 应用程序,但数据库没有使用 DbInitializer 中定义的数据作为种子。 编辑:我发现将DbInitializer中的代码添加到Home Controller中的Index方法中,数据被播种到了数据库中

【问题讨论】:

好吧,做一些基本的调试。那里有很好的种子方法。它曾经被调用过吗?你知道,在我们花时间调试之前,我们会有点期待。只需一个不错的小断言或断点,您就知道了。 【参考方案1】:

希望以下网址对您有所帮助。

Seed data EF core

【讨论】:

以上是关于知道为啥我的 DbInitializer 中的数据没有填充到我的数据库中的主要内容,如果未能解决你的问题,请参考以下文章

Webpack 从我的样式表中的内联 SVG 中去除标签,我不知道为啥

我不知道为啥多线程编码不能减少我的代码中的计算时间

为啥 MariaDB 不接受我的字符串变量作为我的 sql 查询中的表名?

知道为啥 MSBuild 会突然开始对我的解决方案中的其他项目执行代码分析吗?

为啥我的服务器没有监听客户端发出的数据?

编辑后不刷新 ALV。为啥?