asp.net-core - 无法创建“DataContext”类型的对象。对于设计时支持的不同模式
问题描述
我有一个包含多个项目的解决方案。我有一个名为“Persistence”的项目,其中有数据库上下文的代码。我有一个实体域项目,我有一个 API 项目,将在前端应用程序中使用。
我在 Persistence 项目中的 DataContext.cs 文件如下所示:
using System;
using Domain;
using Microsoft.EntityFrameworkCore;
namespace Persistence
{
public class DataContext: DbContext
{
public DataContext(DbContextOptions options) : base(options){}
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=testDB;Integrated Security=True");
}
}
}
当 CD 在持久性项目中并运行此命令时:
dotnet ef migrations add initcreate -s ..\API\
我收到此错误:
无法创建“DataContext”类型的对象。有关设计时支持的不同模式,请参阅 https://go.microsoft.com/fwlink/?linkid=851728
总的来说,我对实体框架和 .net 仍然很陌生,感谢任何帮助和指导。
谢谢。
解决方案
您会收到该错误,因为要生成迁移,您需要:
- 具有默认构造函数(即无参数构造函数)的 DbContext
- 能够从ApplicationServices获取DbContext(也就是依赖注入)
- 返回正确配置的 DbContext 的设计时工厂。
希望这可以帮助。
推荐阅读
- html - 如何垂直对齐动态长度的文本,同时让它环绕浮动图像?
- python - 为什么 base64.b64encode 返回值 b'somestring' 而不是简单的 'somestring'?
- python - 如何在 Outlook (2010) 全局地址列表中搜索多个名称?
- angular - 角度字符串插值在 JSON 对象值上打印空字符串
- python - 需要有关 python 描述符功能的帮助
- android - Dart 项目可以拥有的最大方法数是多少?
- python - 在反向查询(related_name)中检索 Django QuerySet 匹配字段
- powershell - 从 PowerShell 使用 WinSCP .NET 程序集时“找不到类型 [WinSCP.RemotePath]”
- java - scala计算读取文件中包含的列表中的字符串
- c - while 循环的链表问题,我应该使用 continue 吗?