在asp.netcore迁移中,没有为此对象定义无参数构造函数 [英] No parameterless constructor defined for this object in asp.netcore migrations

查看:287
本文介绍了在asp.netcore迁移中,没有为此对象定义无参数构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ASP.NET Core的新手.使用VS Code学习新版本的.NET Core 2.0.使用迁移创建数据库时遇到问题.首先,它给出了IDesignTimeDbContextFactory的实现例外.解决此问题后,它仍然给出

I am new to ASP.NET Core. learning new version of .NET Core 2.0 using VS Code. I got stuck while doing creating database using migration. First, it gives an exception of implementation of IDesignTimeDbContextFactory. After solving this, it still gives an exception of

没有为此对象定义无参数构造函数

No parameterless constructor defined for this object

这是我的DbContextClass代码:

Here's my code for DbContextClass:

public VegaDbContext CreateDbContext(string[] args)
{
    IConfigurationRoot configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .Build();
    var builder = new DbContextOptionsBuilder<VegaDbContext>();
    var connectionString = 
    configuration.GetConnectionString("DefaultConnection");
    builder.UseSqlServer(connectionString);
    return new VegaDbContext(builder.Options);
}

推荐答案

在尝试ef core时,我尝试了几种方法.我也面临类似的问题.最终,我发现服务效果很好.首先,您需要使用以下覆盖构造函数创建DBContext:

I had tried a couple of ways when I was experimenting with ef core. I faced similar issues too. Finally I found services working great. First you will need to create your DBContext with the following override constructor:

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

在启动时,您可以像这样将上下文添加为服务:

In your start up, you can add your context as a service like this:

services.AddDbContext<ApplicationDBContext>(config => {
    config.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
});

您可以在此处详细了解有关依赖项注入如何工作的信息: https://docs.microsoft.com/zh-cn/aspnet/核心/基础知识/依赖注入

You can read in full detail about how dependency injection works here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection

这部分应该可以帮助您进行迁移.您可以使用dotnet ef命令 https:/执行迁移/docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet .

This part should help you with the migration. You can perform your migrations using the dotnet ef commands https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet.

使用数据库上下文时,请确保使用依赖注入,以便充分利用AddDbContext函数并使它保持DRY.

When using your db context, do ensure that you are using dependency injection so you make full use of the AddDbContext function and keep it DRY.

这篇关于在asp.netcore迁移中,没有为此对象定义无参数构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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