2

We have .net core application that was working fine with 2.0. Since we upgrade it to 2.1 we are getting NRE error .

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

Below are the tables

Item 
-------------
ID
Comment

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

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

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

As commented above, if I comment out one of those line then it works fine but I have both of those lines enable then it throw null reference exception. I do get data when using one of those line at a time.

Thanks

Bhavesh
  • 485
  • 1
  • 8
  • 20
  • I had similar problem. I debugged EF Core 2.1 using Resharper and found that I had an object in the select clause like this - 'property' = object != null and here object was null. So I moved this null check out of the EF query. And once the results from DB came back, then I did foreach on the result set and updated the 'property'. – Varun Sharma Jun 07 '18 at 22:32

1 Answers1

0

Since getAllItem is async, it will return immediately. You need to await this line:

var a = await repo.getAllItem();

Scottie
  • 10,410
  • 17
  • 62
  • 103