Reputation: 6487
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)
Upvotes: 1
Views: 5049
Reputation: 3582
If your collection is not null
, then in your razon view you can use
Model.myCustomers.Any() ? Model.myCustomers.First().Name : string.Empty;
If for some reason you can not avoid your collection to be null, I guess you can do something like this.
Model.myCustomers == null ? string.Empty : Model.myCustomers.Any()
? Model.myCustomers.First().Name : string.Empty;
Upvotes: 1
Reputation: 42384
I cannot iterate through all the properties due to layout design issues.
I'm not exactly clear on what this means, but could you not do something like this?
@if (Model.myCustomers == null || !Model.myCustomers.Any())
{
<p>No customer found.</p>
}
@else
{
[ put the markup for each property here ]
}
Upvotes: 1
Reputation: 62300
Collection or enumerable should never return null value for best practice.
Once you make sure that myCustomers is not null, you will only need to check myCustomers's first item is not null.
var customer = Model.myCustomers.FirstOrDefault();
if (customer != null)
{
var name = customer.Name;
}
Upvotes: 2