对象引用为空.除非它不是空的?

  • 本文关键字:对象引用 c#
  • 更新时间 :
  • 英文 :


我的命令行说我的GetProvinces方法列表的省份没有参考集…但我有99.99999%的把握有人知道发生了什么吗?

控制台错误信息:

dotnet-ef migrations add InitialCreate -o Data/Migrations
Build started...
Build succeeded.

实体框架工具版本'5.0.10'比运行时版本'5.0.11'老。为最新的特性和错误修复更新工具。
系统。NullReferenceException:对象引用没有设置为对象的实例。

at MyApp.Data. sampledata . getprovinces () in C:UsersOwnerDownloadsCOMP 3973 in progressCOMP3973-lab4_A01045801-Michael-GreenMyAppDataSampleData.cs:line 10
at MyApp.Data. applicationdbcontext . getprovinces ()OnModelCreating(ModelBuilder ModelBuilder) in C:UsersOwnerDownloadsCOMP 3973 in progressCOMP3973-lab4_A01045801-Michael-GreenMyAppDataApplicationDbContext.cs:line 22
at microsoft . entityframeworkcore . infrastruct.modelcustomizer。定制(ModelBuilder ModelBuilder, DbContext context)
在Microsoft.EntityFrameworkCore.Infrastructure.ModelSource。CreateModel(DbContext context, iconconvonsetbuilder, convonsetbuilder, ModelDependencies ModelDependencies)

GetProvinces()方法和类基本:

using System.Collections.Generic;
using MyApp.Data;
namespace MyApp.Data 
{
public class SampleData
{
// Method for dummy provinces
public static List<Province> GetProvinces()
{
List<Province> provinces = new List<Province>(){
new Province() {
ProvinceCode = "BC",
ProvinceName = "British Columbia",
Cities = {"Vancouver", "Victoria", "Port Coquitlam"}
},
new Province(){
ProvinceCode = "AB",
ProvinceName = "Alberta",
Cities = {"Calgary", "Edmonton", "Banff"}
},
new Province(){
ProvinceCode = "SK",
ProvinceName = "Saskatchewan",
Cities = {"Moose Jaw", "Regina", "Saskatoon"}
},
};
return provinces;
}
}
}

ApplicationDbContext模型创建:

public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder) 
{
base.OnModelCreating(modelBuilder);

modelBuilder.Entity<Province>().HasData(SampleData.GetProvinces());
modelBuilder.Entity<City>().HasData(SampleData.GetCities());
}
public DbSet<Province> Provinces { get; set; }
public DbSet<City> Cities { get; set; }
}

省模型类:

public class Province 
{
[Key]
[Display (Name="Province Code")]
[MaxLength(2)]
public string ProvinceCode { get; set; } 
[Display (Name="Province Name")]
[MaxLength(30)]
public string ProvinceName { get; set; }
[Display (Name="Cities")]
[MaxLength(50)]
public List<string> Cities { get; set; }
}

我做了一个非常类似的应用,有团队和玩家;它很好地生成了我的迁移…所以我不确定这里发生了什么>;/看看其他3个>;对象没有被设置为对象的实例&;这里有问题,没有一个是直接适用的。

如有任何帮助,不胜感激:D

原因如下:

Cities = {"Vancouver", "Victoria", "Port Coquitlam"}

它所做的是将指定的项目添加到Cities集合中,但它不创建集合。此语法主要用于填充只读集合属性。你没有在Province的构造函数中初始化Cities,所以它是空的,当你试图将项目添加到空集合时,你有NullReferenceException。在Province的构造函数中初始化Cities或使用另一种语法:

Cities = new List<string>() {"Vancouver", "Victoria", "Port Coquitlam"}

此命令初始化集合并向其添加项。

相关内容