我们的.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();
}
以下是表格
Item
-------------
ID
Comment
Ch2
--------------
ID
ItemID
Age
Name
Ch2
--------------
ID
ItemID
Age
Name
Relation
Place
Ch2CH3
--------------
ID
Ch2ID
Ch3ID
如上所述,如果我注释掉其中一行,那么它工作正常,但我有这两行启用然后它抛出空引用异常。我一次使用其中一行时获取数据。
由于
答案 0 :(得分:0)
由于getAllItem是异步的,因此会立即返回。你需要等待这一行:
var a = await repo.getAllItem();