I am using MVC3, Razor, C#.
I have a some Razor code which include some LINQ. It tries to get a value from a List. Sometimes the List is null. At present the application is raising a null exception due to this ie "myCustomers" is null.
The code:
Model.myCustomers.First().Name
Basically "myCustomers" is defined as:
public List<Customer> myCustomers
And populated by a "LINQ to Entity" Query.
If "myCustomers" is null, how can I ensure the razor code does not crash. I do not want to write lots of "if (Name!=null)" type blocks for each property. I cannot iterate through all the properties due to layout design issues. So I need to alter:
Model.myCustomers.First().Name
in some way.
Hopefully this question is not too confusing !
many thanks in advance.
EDIT 1
I like the logic with not returning nulls, but empty lists. I tried using something like
return this._myCustomers ?? Enumerable.Empty<Customers>().ToList();
It would be ideal to have someway to test this in the one line of LINQ in the Razor page for being empty rather than in an "IF" block.
EDIT 2
public static TValue SafeGet<TObject, TValue>(
this TObject obj,
Func<TObject, TValue> propertyAccessor)
{
return obj == null ? default(TValue) : propertyAccessor(obj);
}
So:
Model.myCustomers.FirstOrDefault().SafeGet(m=>m.Name)