How do I deal with iterating over a one to many (or zero) entity when there are zero/null entry?

c# entity-framework-core linq


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?

1/19/2019 4:40:05 PM

Popular Answer

As I said in a comment, you should do this in one statement:

vm.List = _context.Person
    .Select(p => new IndexListItem
        Name = p.Name,
        Address = p.Address.FirstLine + " " + p.Address.SecondLine,
        ID = p.ID

This has two advantages:

  1. It's translated into SQL, so only the four required fields are pulled from the database (which makes a considerable difference with wider records).
  2. EF will generate SQL that takes null values into account.

If you don't want " " as result you could do...

Address = (p.Address.FirstLine + " " + p.Address.SecondLine).Trim()


Address = p.Address.FirstLine != null ? p.Address.FirstLine + " " : "")
    + p.Address.SecondLine

But I don't think it matters much for viewing data.

1/21/2019 6:56:52 PM

Related Questions


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