获取实体框架核心 1.1 的空异常

Posted

技术标签:

【中文标题】获取实体框架核心 1.1 的空异常【英文标题】:Getting Null Exception for Entity Framework core 1.1 【发布时间】:2016-11-22 14:38:32 【问题描述】:

我收到配置服务的空异常。我正在使用 Entity Framework 1.1,以前使用过 core 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"

数据库上下文

 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();

【问题讨论】:

你能测试一下 Configuration.GetConnectionString("UCASAppDatabase") 返回什么吗? 把所有 appsetting.json 并尝试使用 Configuration["Data:ConnectionStrings:UCASAppDatabase"]) 获取连接字符串 嗯,我得到了 Configuration["Data:ConnectionStrings:UCASAppDatabase"]) 的空值 What is a NullReferenceException, and how do I fix it?的可能重复 @CodeCaster 我撤回了我的近距离投票。 【参考方案1】:

找到答案,需要对appsettings.json中的connection-String进行排序

"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();
    

【讨论】:

答案与:jakeydocs.readthedocs.io/en/latest/data/entity-framework-6.html【参考方案2】:

按照惯例,该文件应称为 appsettings.json,而不是 appsetting.json。你能确保你的启动文件引用正确吗?

【讨论】:

它是appsettings.json,错过了写我的问题,也在底部更新我的问题【参考方案3】:

我遇到了同样的问题。在我的属性类中,我刚刚添加了主键属性的键 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; 

    

【讨论】:

以上是关于获取实体框架核心 1.1 的空异常的主要内容,如果未能解决你的问题,请参考以下文章

在实体框架核心中获取最新记录

在实体框架.net核心中获取无效的列名“CompanyLocationId”

获取地图上的空指针异常

实体框架核心 1.1.1 为连接字符串引发 ArgumentNullException

当我从数据库 Web Api .Net 中获取数据时的空列表

如何使用实体框架连接三个表来获取所有数据