问题描述
在以下控制台应用程序(.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
出现以下运行时错误?
AddDbContext 是通过配置调用的,但是上下文类型MyContext"只声明了一个无参数的构造函数.这意味着永远不会使用传递给 AddDbContext 的配置
推荐答案
正如错误所说,如果你通过 AddDbContext
配置你的 MyContext
那么你也需要添加一个构造函数将 DbContextOptions
类型的参数接收到您的 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"只声明了一个无参数的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!