获取Entity Framework核心1.1的空例外

时间:2016-11-22 14:38:32

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

我正在为配置服务获取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();

3 个答案:

答案 0 :(得分:5)

找到答案,需要在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();
    }

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我有同样的问题。在我的属性类中,我只为主键属性添加了键DataAnnotations,如下所示,错误已解决。

import matplotlib.pyplot as plt
import pytesseract
from PIL import Image
from nltk.tokenize import sent_tokenize, word_tokenize

image = Image.open('printer1.jpg')
print(image.info['dpi'])
image.save("new_img.jpg", dpi=(400,400)) # increased the dpi and saved it

new_img = Image.open('new_img.jpg')
width, height = new_img.size

new_size = width*2, height*2
new_img = new_img.resize(new_size, Image.LANCZOS) #sampling
new_img = new_img.convert('L') #converted it to grayscale

new_img = new_img.point(lambda x: 0 if x < 180 else 255, '1') 
#evaluatingevery single pixel in the image for binarization

plt.imshow(new_img)
plt.show()

text = pytesseract.image_to_string(new_img)
text_array = word_tokenize(text)
print(text_array)

Name_Data = text_array[text_array.index('Proof')+2 : 
text_array.index('FIRST')-1]
print(Name_Data)

Name = ""
for i in Name_Data:
   if i == 'I':
       pass
   else:
       Name += i

print(Name)