簡體   English   中英

EF Core HasData() 未在 OnModelCreating 中調用

[英]EF Core HasData() not being called inside OnModelCreating

我在使用英特爾芯片 Mac。

當我執行do.net run時,我希望創建表Player ,並從ApplicationDbContext.cs播種數據。 我看到正在創建表,但沒有插入數據。

我的實現是非常基本的 SQLite 數據庫,但不確定為什么它不起作用?

Output:

在此處輸入圖像描述

播放器.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",
                }
            );
        }
    }
}

程序.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();

無論如何,我試了一下,終於能夠使用以下步驟進行修復:

  1. 刪除現有的 app.db。
  2. 重新創建一個空白的 app.db 文件。
  3. 現在將HasData添加到上下文中。
  4. 使用do.net-ef migrations add CreateTables -o Data/Migrations重新遷移模型
  5. do.net run以播種,現在應該可以工作了。

我不確定為什么問題首先發生。 也許我的原始設置是在Program.cs中遷移之前嘗試從ApplicationDbContext.cs播種。 要點是我應該在運行遷移之前放置HasData

屏幕截圖中箭頭上方的 2 行解釋了該錯誤:'PLAYERID INTEGER NOT NULL CONSTRAINT PK_PLAYERS PRIMARY KEY AUTOINCREMENT'

這意味着數據庫正在嘗試設置 ID 但您正在嘗試自己注入它。 從您的種子中刪除 PlayerId=1。

另外,將 [Key] 屬性添加到 PlayerId 字段,我知道使用 {Id} 是隱式的並且是相同的。 但是您可能希望保持控制並使用密鑰來讓您自己和其他人更清楚這是主密鑰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM