.NET Core 5运行时错误:默认启动配置文件无法应用及JSON反序列化失败
问题求助:.NET Core EF种子数据导入失败
问题背景
我正在学习一门.NET Core课程,在EF模块中发现课程作者拼接了不同时期的录制内容,代码未经演示就发生变更,最终我陷入困境不知如何推进,恳请帮助。
操作步骤与错误信息
我运行了以下命令:
PS I:\Users\Ron\Projects\MVC\DutchTreat> dotnet run /seed
得到错误:
The launch profile "(Default)" could not be applied. A usable launch profile could not be located. Unhandled exception. System.Text.Json.JsonException: The JSON value could not be converted to System.Collections.Generic.IEnumerable`1[DutchTreat.Data.Entities.Product]. Path: $ | LineNumber: 0 | BytePositionInLine: 1. at System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType) at System.Text.Json.Serialization.Converters.IEnumerableDefaultConverter`2.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, TCollection& value) at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value) at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadCore[TValue](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadCore[TValue](Utf8JsonReader& reader, Type returnType, JsonSerializerOptions options) at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, Type returnType, JsonSerializerOptions options) at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options) at DutchTreat.Data.DutchSeeder.Seed() in I:\Users\Ron\Projects\MVC\DutchTreat\Data\DutchSeeder.cs:line 34 at DutchTreat.Program.RunSeeding(IHost host) in I:\Users\Ron\Projects\MVC\DutchTreat\Program.cs:line 41 at DutchTreat.Program.Main(String[] args) in I:\Users\Ron\Projects\MVC\DutchTreat\Program.cs:line 26
相关代码
DutchContext.cs
using DutchTreat.Data.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Ini; using Microsoft.IdentityModel.Tokens; using System; namespace DutchTreat.Data { public class DutchContext : DbContext { private readonly IConfiguration _config; public DutchContext(IConfiguration config) { _config = config; } public DbSet<Product> Products { get; set; } public DbSet<Order> Orders { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseSqlServer(_config["ConnectionStrings:DutchContextDb"]); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Order>() .HasData(new Order() { Id=1, OrderDate=DateTime.UtcNow, OrderNumber="12345" }); } } }
DutchSeeder.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.Json; using System.Threading.Tasks; using DutchTreat.Data.Entities; using Microsoft.AspNetCore.Hosting; namespace DutchTreat.Data { public class DutchSeeder { private readonly DutchContext _ctx; private readonly IWebHostEnvironment _env; public DutchSeeder(DutchContext ctx,IWebHostEnvironment env) { _ctx = ctx; _env = env; } public void Seed() { _ctx.Database.EnsureCreated(); if (!_ctx.Products.Any()) { // 生成示例数据 var filePath = Path.Combine(_env.ContentRootPath,"Data/art.json"); var json = File.ReadAllText(filePath); var products = JsonSerializer.Deserialize<IEnumerable<Product>>(json); _ctx.Products.AddRange(products); var order = new Order() { OrderDate = DateTime.Today, OrderNumber = "10000", Items = new List<OrderItem>() { new OrderItem() { Product=products.First(), Quantity=5, UnitPrice=products.First().Price } } }; _ctx.Orders.Add(order); _ctx.SaveChanges(); } } } }
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DutchTreat.Data; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using System.IO; namespace DutchTreat { public class Program { public static void Main(string[] args) { //var host = BuildWebHost(args); var host = CreateHostBuilder(args).Build(); if (args.Length == 1 && args[0].ToLower() =="/seed") { RunSeeding(host); return; } host.Run(); } private static void RunSeeding(IHost host) { var scopeFactory = host.Services.GetService<IServiceScopeFactory>(); using (var scope = scopeFactory.CreateScope()) { var seeder = scope.ServiceProvider.GetService<DutchSeeder>(); seeder.Seed(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration(SetupConfiguration) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); private static void AddConfiguration(HostBuilderContext ctx, IConfigurationBuilder bldr) { bldr.Sources.Clear(); bldr.SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config.json") .AddEnvironmentVariables(); } private static void SetupConfiguration(HostBuilderContext ctx, IConfigurationBuilder builder) { // 移除默认配置选项 builder.Sources.Clear(); builder.AddJsonFile("config.json", false, true) .AddEnvironmentVariables(); } } }
Startup.cs
using DutchTreat.Controllers; using DutchTreat.Data; using DutchTreat.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; namespace DutchTreat { public class Startup { // 运行时会调用此方法,用于向容器添加服务 public void ConfigureServices(IServiceCollection services) { services.AddDbContext<DutchContext>(); services.AddTransient<DutchSeeder>(); services.AddTransient<IMailService,NullMailService>(); //services.AddControllersWithViews(); services.AddControllersWithViews().AddRazorRuntimeCompilation(); services.AddRazorPages(); } // 运行时会调用此方法,用于配置HTTP请求管道 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //app.UseDefaultFiles(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/error"); } app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(cfg => { cfg.MapRazorPages(); cfg.MapControllerRoute("Default", "/{controller}/{action}/{id?}", new { controller = "App", action = "Index" }); }); } } }
launchSettings.json
{ "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Production" } } }, "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:8888", "sslPort": 0 } } }
内容的提问来源于stack exchange,提问作者user1372603
相关产品推荐
相关产品推荐

