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
相关产品推荐
相关产品推荐

