I keep getting NullReferenceException
trying to iterate over a null entry on a row.
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
public int AddressID { get; set; }
}
public class Address
{
public int ID { get; set; }
public string FirstLine { get; set; }
public string SecondLine { get; set; }
}
With the default scaffold template, _context.Person.Include(c => c.Address);
The view works fine if there is an address or not.
However, I'm now replacing the default index page with a newer grid that loads via AJAX with filtering and paging mechanism. For this, I need to convert the data to my ViewModel
I want to be able to display the address in line as text. I've tried the following:
var tmp = _context.Person.Include(x => x.Address).ToList();
tmp.ForEach(x => vm.List.Add(new IndexListItem()
{
Name = x.Name,
Address = x.Address.FirstLine + " " + x.Address.SecondLine,
ID = x.ID
}));
But, when debugging, Address seems to always be null, even if there is data on the row.
I'm pretty sure I can do this on a standard foreach loop, and doing an if null check, but, I can't help but feel this is something that is quite simple and I'm over complicating it.
Is there a simpler way to return the address details I need?
_context.Person.Select(p => new IndexListItem {Name = p.Name, Address = p.Address.FirstLine + " " + p.Address.SecondLine, ... }
._context.Person.Include(c => c.Address)
didn't seem to change and that should always do the same thing.