首页 > 解决方案 > 无法创建“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 仍然很陌生,感谢任何帮助和指导。

谢谢。

标签: asp.net-coreentity-framework-core

解决方案


您会收到该错误,因为要生成迁移,您需要:

  1. 具有默认构造函数(即无参数构造函数)的 DbContext
  2. 能够从ApplicationServices获取DbContext(也就是依赖注入)
  3. 返回正确配置的 DbContext 的设计时工厂。

希望这可以帮助。


推荐阅读