AddDbContext是通过配置调用的,但是上下文类型“ MyContext”仅声明无参数的构造函数? [英] AddDbContext was called with configuration, but the context type 'MyContext' only declares a parameterless constructor?

查看:1179
本文介绍了AddDbContext是通过配置调用的,但是上下文类型“ MyContext”仅声明无参数的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下控制台应用程序(.Net core 2.0)中, scaffold-dbcontext 创建了以下 DbContext

In the following console application (.Net core 2.0), the scaffold-dbcontext created the following DbContext

public partial class MyContext : DbContext
{
    public virtual DbSet<Tables> Tables { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(Program.Conn); }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder) { .... }
}

在Main()中( static void Main(string [] args)),以下代码

In the Main() (static void Main(string[] args)), the following code

var services = new ServiceCollection();
var conn = configuration.GetConnectionString("MySource");
services.AddDbContext<MyContext>(o => o.UseSqlServer(conn)); // Error

得到以下运行时错误?

got the following run-time error?


AddDbContext是通过配置调用的,但是上下文类型 MyContext仅声明无参数的构造函数。这意味着将永远不会使用传递给AddDbContext的配置

AddDbContext was called with configuration, but the context type 'MyContext' only declares a parameterless constructor. This means that the configuration passed to AddDbContext will never be used


推荐答案

如果通过 AddDbContext 配置 MyContext ,那么您也需要添加一个接收参数为<$ c $类型的构造函数。 c> DbContextOptions< MyContext> 放入您的 MyContext 类中,如下所示

As the error said it if you configure your MyContext through AddDbContext then you need too add a constructor that receive a parameter of type DbContextOptions<MyContext> into your MyContext class like below

public MyContext(DbContextOptions<MyContext> options)
    : base(options)
{ }

如果不这样做,ASP.Net Core将无法注入使用 AddDbContext 设置的配置。

If you don't do that, ASP.Net Core will not be able to inject the configuration you set with AddDbContext.

这篇关于AddDbContext是通过配置调用的,但是上下文类型“ MyContext”仅声明无参数的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆