Home > Software design >  Getting relative item of an specific entity by id returns System.ArgumentNullException
Getting relative item of an specific entity by id returns System.ArgumentNullException

Time:11-26

I have a diagram like below picture and I use entity framework. enter image description here I want to retrieve OutOfServices items based on the Id of Calenders table. I used this syntax like below which leads to the error "System.ArgumentNullException:

'Value cannot be null. (Parameter 'source')'"

     public IList<OutOfService> GetRoomOutOfServiceDatesByCalendarId(int calendarId)
    {
        IList<OutOfService> outOfServices = _myDbContext.Calenders.Find(calendarId).OutOfServices.ToList();

        return outOfServices;
    }

CodePudding user response:

I did it this way and it is ok now

     IList<OutOfService> outOfServices = _myDbContext.OutOfServices.Where(x=>x.Calender.Calender_id== calendarId).ToList();

I think the problem relates to lazy loading

CodePudding user response:

This is happening because there are no outofservices for the given calendar id. You might rewrite this code a bit with null check

 public IList<OutOfService> GetRoomOutOfServiceDatesByCalendarId(int calendarId)
{
    var outOfService=_myDbContext.Calenders.Find(calendarId);
    IList<OutOfService> outOfServices = outOfService!=null && outOfService.OutOfServices!=null?outOfService.OutOfServices.ToList():null;

    return outOfServices;
}
  • Related