EF Core HasData() 未在 OnModelCreating 中调用
EF Core HasData() not being called inside OnModelCreating
我使用的是 Intel 芯片 Mac。
当我执行 dotnet run
时,我希望创建 table Player
,并从 ApplicationDbContext.cs
播种数据。我看到正在创建 table,但没有插入数据。
我的实现对 SQLite 数据库非常基础,但不确定为什么它不起作用?
输出:
Player.cs
namespace OneModel.Models
{
public class Player
{
public int PlayerId { get; set; }
public string PlayerName { get; set; }
public Player()
{
}
}
}
ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
using OneModel.Models;
namespace OneModel.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Player> Players { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Player>().HasData(
new
{
PlayerId = 1,
PlayerName = "Edgar",
}
);
}
}
}
Program.cs
using Microsoft.EntityFrameworkCore;
using OneModel.Data;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(connectionString));
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
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.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
using (var scope = app.Services.CreateScope()) {
var services = scope.ServiceProvider;
var context = services.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
}
app.Run();
屏幕截图中箭头上方两行解释了错误:'PLAYERID INTEGER NOT NULL CONSTRAINT PK_PLAYERS PRIMARY KEY AUTOINCREMENT'
这意味着数据库正在尝试设置 ID 但您正在尝试自己注入它。从你的种子中删除 PlayerId=1。
另外,在PlayerId字段中添加[Key]属性,我知道使用{Id}是隐式的,也是一样的。但您可能希望保持控制并使用密钥让您自己和其他人更清楚这是主键。
无论如何,我试了一下,终于能够使用以下步骤进行修复:
- 删除现有的app.db。
- 重新创建一个空白 app.db 文件。
- 现在将
HasData
添加到上下文中。
- Re-migrate 使用
dotnet-ef migrations add CreateTables -o Data/Migrations
的模型
dotnet run
再次播种,现在应该可以了。
我不确定为什么会出现这个问题。也许我最初的设置是在 Program.cs
迁移之前尝试从 ApplicationDbContext.cs
播种。要点是我应该在 运行 迁移之前放置 HasData
。
我使用的是 Intel 芯片 Mac。
当我执行 dotnet run
时,我希望创建 table Player
,并从 ApplicationDbContext.cs
播种数据。我看到正在创建 table,但没有插入数据。
我的实现对 SQLite 数据库非常基础,但不确定为什么它不起作用?
输出:
Player.cs
namespace OneModel.Models
{
public class Player
{
public int PlayerId { get; set; }
public string PlayerName { get; set; }
public Player()
{
}
}
}
ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
using OneModel.Models;
namespace OneModel.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Player> Players { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Player>().HasData(
new
{
PlayerId = 1,
PlayerName = "Edgar",
}
);
}
}
}
Program.cs
using Microsoft.EntityFrameworkCore;
using OneModel.Data;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(connectionString));
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
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.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
using (var scope = app.Services.CreateScope()) {
var services = scope.ServiceProvider;
var context = services.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
}
app.Run();
屏幕截图中箭头上方两行解释了错误:'PLAYERID INTEGER NOT NULL CONSTRAINT PK_PLAYERS PRIMARY KEY AUTOINCREMENT'
这意味着数据库正在尝试设置 ID 但您正在尝试自己注入它。从你的种子中删除 PlayerId=1。
另外,在PlayerId字段中添加[Key]属性,我知道使用{Id}是隐式的,也是一样的。但您可能希望保持控制并使用密钥让您自己和其他人更清楚这是主键。
无论如何,我试了一下,终于能够使用以下步骤进行修复:
- 删除现有的app.db。
- 重新创建一个空白 app.db 文件。
- 现在将
HasData
添加到上下文中。 - Re-migrate 使用
dotnet-ef migrations add CreateTables -o Data/Migrations
的模型
dotnet run
再次播种,现在应该可以了。
我不确定为什么会出现这个问题。也许我最初的设置是在 Program.cs
迁移之前尝试从 ApplicationDbContext.cs
播种。要点是我应该在 运行 迁移之前放置 HasData
。