无法使用 EF Core 为数据库播种
Unable to seed database with EF Core
我正在重新创建我的 MVC asp.net 核心,但这次我使用 ASP.NET Identity,因为它内置了 register/log-in。
我注意到的唯一区别是数据库是 startup.cs 文件中的“默认连接”,但我不确定为什么这会改变您为数据库设置种子的方式。当我 运行 项目时,我没有收到任何构建错误或异常,但数据库没有种子,并且当我 运行 在 Web 应用程序中尝试单击某些内容时出现 404 错误。
这正是我的文件在我的其他 ASP.NET 核心项目中的样子,它工作正常,所以我不知道这里的问题是什么。如果有人可以帮助我,我将不胜感激。谢谢!
这是我的 Startup.cs 文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using EasyEats.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using EasyEats.Models;
namespace EasyEats
{
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.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
}
// 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.UseDatabaseErrorPage();
}
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();
});
//SeedData.Initialize(app.ApplicationServices);
}
}
}
我读到最后一行 (SeedData.Initialize) 应该为数据库设置种子,但我却收到一条错误消息:
"System.InvalidOperationException: 'Cannot resolve scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions`1[EasyEats.Data.ApplicationDbContext]' from root provider.'
所以我暂时把它注释掉了。
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using EasyEats.Data;
using EasyEats.Models;
namespace EasyEats
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
SeedData.Initialize(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
SeedData.cs(在模型文件夹中)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using EasyEats.Data;
namespace EasyEats.Models
{
public class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new ApplicationDbContext(
serviceProvider.GetRequiredService<
DbContextOptions<ApplicationDbContext>>()))
{
// Look for any movies.
if (context.Restaurants.Any())
{
return; // DB has been seeded
}
context.Restaurants.AddRange(
new Restaurant
{
RestaurantName = "McDonalds",
RestaurantDescription = "McDonald's Corporation sells hamburgers, chicken sandwiches, French fries, soft drinks, breakfast items, and desserts.",
},
new Restaurant
{
RestaurantName = "Burger King",
RestaurantDescription = "Burger King Corporation, restaurant company specializing in flame-broiled fast-food hamburgers.",
},
new Restaurant
{
RestaurantName = "Chipotle",
RestaurantDescription = "Chipotle is a fast-casual chain that's known for its build-your-own burritos, rice bowls, and other Mexican dishes.",
},
new Restaurant
{
RestaurantName = "Chick-fil-A",
RestaurantDescription = "Chick-fil-A is one of the largest American fast food restaurant chains and the largest whose specialty is chicken sandwiches.",
}
);
context.SaveChanges();
}
}
}
}
ApplicationDbContext.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using EasyEats.Models;
namespace EasyEats.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Restaurant> Restaurants { get; set; }
public DbSet<MenuItem> MenuItems { get; set; }
public DbSet<CartItem> CartItems { get; set; }
}
}
我正在使用两个教程作为参考:
您在 ConfigureServices
方法中注册了您的 ApplicationDbContext
两次:
services.AddScoped<ApplicationDbContext>();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
尝试删除作用域注册并检查它是否解决了问题。
其实你只需要删除你里面的代码Program.cs
:
CreateHostBuilder(args).Build().Run();
然后重新运行您的项目并检查数据库。
我正在重新创建我的 MVC asp.net 核心,但这次我使用 ASP.NET Identity,因为它内置了 register/log-in。
我注意到的唯一区别是数据库是 startup.cs 文件中的“默认连接”,但我不确定为什么这会改变您为数据库设置种子的方式。当我 运行 项目时,我没有收到任何构建错误或异常,但数据库没有种子,并且当我 运行 在 Web 应用程序中尝试单击某些内容时出现 404 错误。
这正是我的文件在我的其他 ASP.NET 核心项目中的样子,它工作正常,所以我不知道这里的问题是什么。如果有人可以帮助我,我将不胜感激。谢谢!
这是我的 Startup.cs 文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using EasyEats.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using EasyEats.Models;
namespace EasyEats
{
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.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
}
// 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.UseDatabaseErrorPage();
}
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();
});
//SeedData.Initialize(app.ApplicationServices);
}
}
}
我读到最后一行 (SeedData.Initialize) 应该为数据库设置种子,但我却收到一条错误消息:
"System.InvalidOperationException: 'Cannot resolve scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions`1[EasyEats.Data.ApplicationDbContext]' from root provider.'
所以我暂时把它注释掉了。
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using EasyEats.Data;
using EasyEats.Models;
namespace EasyEats
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
SeedData.Initialize(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
SeedData.cs(在模型文件夹中)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using EasyEats.Data;
namespace EasyEats.Models
{
public class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new ApplicationDbContext(
serviceProvider.GetRequiredService<
DbContextOptions<ApplicationDbContext>>()))
{
// Look for any movies.
if (context.Restaurants.Any())
{
return; // DB has been seeded
}
context.Restaurants.AddRange(
new Restaurant
{
RestaurantName = "McDonalds",
RestaurantDescription = "McDonald's Corporation sells hamburgers, chicken sandwiches, French fries, soft drinks, breakfast items, and desserts.",
},
new Restaurant
{
RestaurantName = "Burger King",
RestaurantDescription = "Burger King Corporation, restaurant company specializing in flame-broiled fast-food hamburgers.",
},
new Restaurant
{
RestaurantName = "Chipotle",
RestaurantDescription = "Chipotle is a fast-casual chain that's known for its build-your-own burritos, rice bowls, and other Mexican dishes.",
},
new Restaurant
{
RestaurantName = "Chick-fil-A",
RestaurantDescription = "Chick-fil-A is one of the largest American fast food restaurant chains and the largest whose specialty is chicken sandwiches.",
}
);
context.SaveChanges();
}
}
}
}
ApplicationDbContext.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using EasyEats.Models;
namespace EasyEats.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Restaurant> Restaurants { get; set; }
public DbSet<MenuItem> MenuItems { get; set; }
public DbSet<CartItem> CartItems { get; set; }
}
}
我正在使用两个教程作为参考:
您在 ConfigureServices
方法中注册了您的 ApplicationDbContext
两次:
services.AddScoped<ApplicationDbContext>();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
尝试删除作用域注册并检查它是否解决了问题。
其实你只需要删除你里面的代码Program.cs
:
CreateHostBuilder(args).Build().Run();
然后重新运行您的项目并检查数据库。