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

梦想与她 提交于 2019-12-11 17:55:26

问题


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:


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

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

...or...

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

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




回答2:


Can you try the address like this:

Address = x.Address?.FirstLine + " " + x.Address?.SecondLine, 

If you don't want white-space, try like below:

Address = x.Address == null ? null : (x.Address.FirstLine + " " + x.Address.SecondLine), 


来源:https://stackoverflow.com/questions/54269201/how-do-i-deal-with-iterating-over-a-one-to-many-or-zero-entity-when-there-are

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!