You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MVC迁移无法更新SQL:自定义模型表未生成求助

问题描述

执行Add-migration First并运行Update-database后,Identity表已创建,但Models中的StockPaints表未生成,迁移文件中也未提及该表。

MODEL

using System.ComponentModel.DataAnnotations;

namespace ICS_Man.Models
{
public class StockPaints
{
    [Key]
    public int Id { get; set; }
    public String PaintCode { get; set; }
}
}

ApplicationDBContext

using ICS_Man.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace ICS_Man.Data;

public class ApplicationDbContext : IdentityDbContext
{ 
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }
    public DbSet<StockPaints> StockPaints { get; set; }
}

Migration File

namespace ICS_Man.Data.Migrations
{
public partial class first : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {

    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {

    }
}
}
解决建议

EF Core生成空迁移文件,说明它没检测到StockPaints实体的变更,按以下步骤排查:

  • 确认DbContext已正确注册到依赖注入
    检查Program.cs(或Startup.cs)中是否有如下配置:

    builder.Services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
    

    若缺少这段代码,EF工具无法识别你的上下文,自然检测不到实体。

  • 执行迁移时指定正确的上下文和项目
    如果是分层项目(比如Data层与Web层分离),执行迁移命令需明确指定上下文和项目:

    Add-Migration First --project ICS_Man.Data --context ApplicationDbContext
    Update-Database --project ICS_Man.Data --context ApplicationDbContext
    

    避免EF工具使用错误的上下文或找不到实体所在项目。

  • 重新编译解决方案
    有时项目未编译,EF工具无法读取新添加的StockPaints实体,先执行一次解决方案重新生成(Build -> Rebuild Solution),再重新生成迁移。

  • 移除无效迁移后重新生成
    先删除当前空的迁移文件,再执行命令移除迁移记录:

    Remove-Migration
    

    之后重新生成迁移并更新数据库:

    Add-Migration First
    Update-Database
    

内容的提问来源于stack exchange,提问作者Steve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 19:25:21