ASP.NET Core MVC无法从JSON导入种子数据问题求助
问题解决方案
一、关于Startup.cs的困惑
ASP.NET Core 6及后续版本采用顶级语句模式,将原Startup.cs中的ConfigureServices和Configure逻辑合并到Program.cs中,你的项目不需要单独创建Startup.cs文件,当前Program.cs的写法完全合规。
二、种子数据导入失败的修复步骤
1. 修复Seeder.cs核心逻辑
你的Seeder类注释掉了将数据添加到上下文的关键代码,同时需要处理JSON反序列化时的未知字段:
using Cenimas.Data.Entities; using System.Text.Json; using Microsoft.EntityFrameworkCore; namespace Cenimas.Data { public class Seeder { private readonly CenimasContext ctx; private readonly IWebHostEnvironment hosting; public Seeder(CenimasContext ctx, IWebHostEnvironment hosting) { this.ctx = ctx; this.hosting = hosting; } public void Seed() { ctx.Database.EnsureCreated(); if (!ctx.Movies.Any()) { var filePath = Path.Combine(hosting.ContentRootPath, "Data/MoviesList.json"); var json = File.ReadAllText(filePath); // 配置反序列化选项,忽略实体中不存在的字段 var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, IgnoreReadOnlyProperties = true, AllowTrailingCommas = true }; var movies = JsonSerializer.Deserialize<IEnumerable<Movies>>(json, options); // 关键:将反序列化后的电影数据添加到上下文 ctx.Movies.AddRange(movies); ctx.SaveChanges(); } } } }
2. 重构CenimasContext构造函数
Program.cs已通过AddDbContext配置连接字符串,Context无需自行注入IConfiguration,改用标准构造:
using Cenimas.Data.Entities; using Microsoft.EntityFrameworkCore; namespace Cenimas.Data { public class CenimasContext : DbContext { public CenimasContext(DbContextOptions<CenimasContext> options) : base(options) { } public DbSet<Movies> Movies { get; set; } } }
3. 配置JSON文件输出属性
右键项目中的Data/MoviesList.json文件,设置:
- 复制到输出目录:如果较新则复制
- 生成操作:内容
4. 正确触发种子数据导入
运行项目时添加/seed参数:
- 命令行:项目根目录执行
dotnet run /seed - Visual Studio调试:右键项目→属性→调试→应用程序参数,输入
/seed
三、额外检查项
- 确认appsettings.json中
DefaultConnection连接字符串指向可用的SQL Server实例 - 确保SQL Server服务正常运行,应用有足够权限操作数据库
内容的提问来源于stack exchange,提问作者Kookki OP
相关产品推荐
相关产品推荐

