Value cannot be null Parameter name: source at System.Linq.Enumerable.Select[TSource,TResult]

c# ef-core-2.0 entity-framework entity-framework-core

Question

I am getting this error for below code.

var person = await context.Person.Where(x=>x.ID == 1).ToControllerModel().SignleOrDefaultAsync();

return person.ToViewModel();

static  IQueryable<Person> ToControllerModel(this IQueryable<Person> query)
        {
            return query.Select(i => new PersionModel{
                Name = i.Name,
                Addresses = (i.Contact != null && i.Contact.Addresses != null) ? i.Contact.Addresses.ToControllerModel() : null //causing error - works if removed
             });
        }


static  IQueryable<Address> ToControllerModel(this IQueryable<Address> query)
{
    return query.select( i => new AddressModel {
            Street = i.Street,
            No = i.No,
            City = i.City,
            Postcode = i.Postcode
   });
}

I have tried different solutions and below seems to be working fine but not sure why. Could anybody explain why this fixes the issue?

Addresses = (i.Contact != null && i.Contact.Addresses != null) ? i.Contact.Addresses.Select(x=>x.ToControllerModel())


static  Address ToControllerModel(this Address query)
{
    return  new AddressModel {
            Street = i.Street,
            No = i.No,
            City = i.City,
            Postcode = i.Postcode
   };
}

I am using EF Core.

1
1
4/11/2018 10:45:14 AM

Popular Answer

You forgot the second part, if Contact or Contact.Addresses is null:

Your line:

Addresses = (i.Contact != null && i.Contact.Addresses != null) ? i.Contact.Addresses.ToControllerModel()

Correct would be:

Addresses = (i.Contact != null && i.Contact.Addresses != null) ? i.Contact.Addresses.ToControllerModel() : <provide default initalizer>
0
4/11/2018 10:54:17 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow