Entity framework EF core 2.1升级空参考异常,即使在检查not Null后也是如此

Entity framework EF core 2.1升级空参考异常,即使在检查not Null后也是如此,entity-framework,linq,.net-core,ef-core-2.0,Entity Framework,Linq,.net Core,Ef Core 2.0,我们的.net核心应用程序在2.0中运行良好。由于我们将其升级到2.1版,因此出现了NRE错误 public class TestController { public async Task<ICollection<BModel>> GetItems() { var a = await repo.getAllItem(); var b = a.FirstOrDefault().Ch2List.ToList(); // throw error here

我们的.net核心应用程序在2.0中运行良好。由于我们将其升级到2.1版,因此出现了NRE错误

public class TestController {

public async Task<ICollection<BModel>> GetItems() {
   var a = await repo.getAllItem();
   var b = a.FirstOrDefault().Ch2List.ToList(); // throw error here
   return Ok(a.ToBModel());
 }

}

public class repo {

 public async Task<ICollection<ItemModel>> GetAllItem() {
        var items = await context.Item.Where(x=> x.IsActive).ToItemModel().ToListAsync();
    return items;
 }

}

public static IQueryable<ItemModel> ToItemModel(this IQuerable<Item> query) {
   return query.select(i => new ItemModel {
    Id = i.Id,
    Ch2List = i.Ch2 != null && i.Ch2.Any() ? i.Ch2.AsQuerable().ToCh2ViewModel() : null,
   Comment = i.Comment
  });
}

public static IQuerable<Ch2Model> ToCh2ViewModel(this IQuerable<Ch2> query) {
    return query.select(i => new Ch2Model {
        No = i.No,
        //commenting one of the below line works but I having both throw NRE
        Ch2s = i.Ch2Ch3 != null && i.Ch2Ch3.Any() ? i.AB.Select(x=>x.Ch2.Age):null,
        ItemID = i.Item != null ? i.Item.ID : null
  });

}

public static ICollection<BModel> ToBModel(this.ICollection<ItemModel> query) {
    retunr query.select(i => new BModel {
         Id = i.Id,
         Ch2List = i.Ch2List?.ToList().ToChModel(),
         Comment = i.Comment,
  }).ToList();
}

public static ICollectio<ChModel> ToChModel(this ICollection<Ch2Model> query) {
   return query.select(i => new ChModel {
      No = i.No,
      Name = i.Name,
      Age = i.Age,
  }).ToList();
}
如上所述,如果我注释掉其中一行,那么它可以正常工作,但我启用了这两行,然后它抛出空引用异常。每次使用其中一行时,我确实会获取数据


谢谢

由于getAllItem是异步的,它将立即返回。您需要等待这一行:


var a=wait repo.getAllItem()

我也有类似的问题。我使用Resharper调试了EF Core 2.1,发现select子句中有这样一个对象-'property'=object!=null,这里的对象为null。所以我把这个空检查移出了EF查询。当DB的结果出来后,我对结果集进行了foreach并更新了“属性”。对不起,这是我的错误,我正在使用wait have update这个问题
Item 
-------------
ID
Comment

Ch2
--------------
ID 
ItemID
Age
Name

Ch2
--------------
ID 
ItemID
Age
Name
Relation
Place

Ch2CH3
--------------
ID
Ch2ID
Ch3ID