Entity Frameworkコア1.1のNull例外の取得

asp.net-core-mvc c# entity-framework-core

質問

configureサービスのnull例外が発生しています。私はEntity Framework 1.1を使用しています。以前はコア1.0を使用していましたが、問題はありません。

Startup.cs - > Services.AddDbContextでエラーが発生しました...

 {System.ArgumentNullException: Value cannot be null.
 Parameter name: connectionString
 at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
at   Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(D bContextOptionsBuilder optionsBuilder, String connectionString, Action`1 sqlServerOptionsAction)
at App.WebDashboard.Startup.<ConfigureServices>b__4_0(DbContextOptionsBuilder options)
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.DbContextOptionsFactory[TContext](IServiceProvider applicationServiceProvider, Action`2 optionsAction)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
at Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Internal.TypeActivatorCache.CreateInstance[TInstance](IServiceProvider serviceProvider, Type implementationType)
at Microsoft.AspNetCore.Mvc.Controllers.DefaultControllerFactory.CreateController(ControllerContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker. <InvokeNextResourceFilter>d__22.MoveNext()}

Startup.cs

 public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddDbContext<TestDbContext>(options =>
           options.UseSqlServer(Configuration.GetConnectionString("UCASAppDatabase")));

        services.AddMvc();
    }

appsetting.jsonの接続文字列

"ConnectionStrings": {
  "UCASAppDatabase": "Data Source=mydatasource;Initial Catalog=UCAS-DB;Integrated Security=True"
}

DbContext

 public class TestDbContext : DbContext
 {
    public TestDbContext(DbContextOptions<TestDbContext> options) : base(options)
    { }

    public DbSet<TestModel> TestModels { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TestModel>().ToTable("TestTable");
    }
}

エンティティクラス

[Table("TestTable")]
public class TestModel
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
}

私がデータを読み込もうとしているコントローラクラス

public class HomeController : Controller
{
    private readonly TestDbContext _context;
    public HomeController(TestDbContext context)
    {
        this._context = context;
    }

    public IActionResult About()
    {
        var query = (from b in _context.TestModels
                     select b).ToList();

        ViewData["Message"] = "Your application description page.";

        return View();
    }

Appsettings.json

 public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

受け入れられた回答

答えを見つけ、appsettings.jsonの接続文字列をソートする必要があります

"Data": {
  "UCASAppDatabase": {
    "ConnectionString": "Data Source=mysource;Initial Catalog=UCAS-DB;Integrated Security=True;Persist Security Info=True"
  }
}

とStartup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddDbContext<TestDbContext>(options =>
           options.UseSqlServer(Configuration["Data:UCASAppDatabase:ConnectionString"]));

        services.AddMvc();
    }

人気のある回答

私は同じ問題を抱えていました。私のプロパティクラスでは、主キー属性のキーDataAnnotationsを次のように追加したところ、エラーが解決しました。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace Treat_Data.Model
{
    public class Restaurant
    {
        [Key]
        public int Restaurant_ID { get; set; }//this is the primary key
        public string Name { get; set; }
        public string Address { get; set; }
        public string Open_Hours { get; set; }

    }
}


Related

ライセンスを受けた: CC-BY-SA with attribution
所属していない Stack Overflow
このKBは合法ですか? はい、理由を学ぶ
ライセンスを受けた: CC-BY-SA with attribution
所属していない Stack Overflow
このKBは合法ですか? はい、理由を学ぶ