【问题标题】:Error when configuring services - Adding Entity Framework Core to ASP.NET Core配置服务时出错 - 将 Entity Framework Core 添加到 ASP.NET Core
【发布时间】:2020-01-27 20:10:24
【问题描述】:

我创建了一个 ASP.NET Core Web 应用程序。我正在尝试将 Entity Framework Core 添加到我的解决方案中。

我已将以下 nugets 安装到项目中。

  • “Microsoft.NETCore.App”,
  • “Microsoft.AspNetCore.App”
  • “Microsoft.EntityFrameworkCore.SqlServer”

上下文中定义了一个 DbSet。

在启动类中,当我尝试添加 Db 上下文时,“配置”中出现以下错误。

名称配置在当前上下文中不存在。

我的代码是:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyContext>(options => 
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}

我在关注this article 配置方面没说太多

【问题讨论】:

  • 您是否在启动时包含了相关的IConfiguration Configuration 属性/字段?
  • 我建议你这个链接来解决问题:stackoverflow.com/a/59653471/5576498
  • @AminGolmahalle 感谢您的回复。我是.Net Core 的新手。我的解决方案中没有 appSettings.json。属性下有一个launchSetting.json。应该如何添加ConnectionString?我应该为此在解决方案中创建一个新的 .json 文件吗?请指教
  • @sm101 了解concpet asp.net core请看这个链接:stackoverflow.com/a/59701684/5576498

标签: c# asp.net-core entity-framework-core


【解决方案1】:

代码示例不完整。 Configuration 实际上是 Startup 类的属性。它是通过构造函数依赖注入填充的。

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MyContext>(options => 
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }

    //...
}

正如article 的最后一步所述:完整代码可在https://github.com/aspnet/AspNetCore.Docs/tree/master/aspnetcore/data/ef-mvc/intro/samples/cu-final 获得

【讨论】:

    猜你喜欢
    • 2017-03-23
    • 2021-02-16
    • 1970-01-01
    • 2020-12-14
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    相关资源
    最近更新 更多