Master Detail Null Reference Error

Hi,

I get a NullReferenceError when the results are empty from a GetChildren data operation.

For example, after creating a page using the Mater/Detail Hierarchy wizard, the code to load the children on RowExpand is this:

${result}.ToList().ForEach(event.ShipmentItems.Add);

suggest changing to this:

if(${result} != null && ${result}.Any()) {${result}.ToList().ForEach(event.ShipmentItems.Add);};

*EDIT: Turns out Any() and Count() methods excute an extra db query so this is preferred:

var res = ${result}.ToList(); if(res.Count != 0){res.ForEach(args.ShipmentItems.Add);}

or better yet, avoid .ForEach():

foreach(var r in ${result}.ToList()){event.ShipmentItems.Add(r);}

Thanks,
Josh

1 Like

Of course you'll get an error.
You invoke .ToList() method from enumerable which is null.

Thanks. I understand that. The code is auto generated. My post is a suggestion to improve the auto generated code. Have a nice day!

and by the way, I believe EF returns an empty enumerable rather than null. ToList() is fine with it but ForEach() is not.