![](/img/trans.png)
[英]EF Core Seed Database OneToMany Relationship with predefined Lists
[英]Unable to seed database with EF Core
我正在重新創建我的 MVC asp.net 內核,但這次我使用的是 ASP.NET Identity,因為它內置了寄存器/登錄。
我注意到的唯一區別是數據庫是 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.'
所以我暫時把它注釋掉了。
程序.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; }
}
}
我使用兩個教程作為參考:
實際上,您只需刪除Program.cs
中的代碼:
CreateHostBuilder(args).Build().Run();
然后重新運行您的項目並檢查數據庫。
您在ConfigureServices
方法中注冊ApplicationDbContext
兩次:
services.AddScoped<ApplicationDbContext>();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
嘗試刪除范圍注冊並檢查它是否解決了問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.