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

EF Core创建迁移报错:无法实例化RepositoryContext

解决ASP.NET Core中创建EF Core迁移时无法创建RepositoryContext的问题

一、修复实体类主键缺失问题

EF Core要求每个实体必须定义主键,你的Apartment和Home类未配置主键,会导致EF Core无法正确映射实体,进而阻碍迁移创建:

  • 修改Apartment类,继承BaseEntity获取主键:
public class Apartment : BaseEntity
{
    public DateOnly ConstructionDate { get; set; }
    public List<Home> Homes { get; set; }
    public List<HomeOwner> HomeOwners { get; set; }
}
  • 修改Home类,继承BaseEntity获取主键:
public class Home : BaseEntity
{
    public string Address { get; set; }
    public Tenant Tenant { get; set; }
    public HomeOwner HomeOwner { get; set; }
}

二、修正SQL Server连接字符串错误

你在OnConfiguring方法中误用了SQLite的连接字符串关键字DataSource,SQL Server应使用Server,修正后的代码:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer("Server=DESKTOP-9MDCD3N;Initial Catalog=ApartmentManagementAppDb;Integrated Security=True;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
}

三、添加设计时上下文工厂(针对类库项目)

由于启动项目是数据访问层类库,EF Core迁移工具需要明确的方式创建上下文实例,在数据访问层项目中添加以下类:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace YourNamespace // 替换为你的实际命名空间
{
    public class RepositoryContextFactory : IDesignTimeDbContextFactory<RepositoryContext>
    {
        public RepositoryContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<RepositoryContext>();
            optionsBuilder.UseSqlServer("Server=DESKTOP-9MDCD3N;Initial Catalog=ApartmentManagementAppDb;Integrated Security=True;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");

            return new RepositoryContext(optionsBuilder.Options);
        }
    }
}

四、验证迁移执行前置条件

确保:

  • 包管理器控制台的「默认项目」已选中数据访问层
  • 解决方案的启动项目设置为数据访问层

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:30:13