سؤال

I have the following, but it's failing with a NullReferenceException:

<td>@item.FundPerformance.Where(xx => fund.Id == xx.Id).FirstOrDefault().OneMonth ?? -</td>

OneMonth is defined as

public virtual decimal? OneMonth { get; set; }

and its value is null at the time that it fails.

I thought the Null Coalesce operator would test if its null and if so, return the value to the right of the operator?

What do I need to change to make this work?

هل كانت مفيدة؟

المحلول

The razor syntax, as you wrote it, ends at "OneMonth". The ?? are interpreted as text. To have it interpreted as razor, you must wrap the whole statements in () like this:

<td>@(item.FundPerformance.Where(xx => fund.Id == xx.Id).FirstOrDefault().OneMonth ?? "-")</td>

This will still get you an error: the left operator is a decimal and the right operator is a string. So you can either render a zero instead of "-" or use ternary operator, with OneMonth.Value.ToString() as left value and "-" as right value.

نصائح أخرى

It's nothing to do with MVC or Razor.

FundPerformance.Where(xx => fund.Id == xx.Id).FirstOrDefault()

will return null if there is no element that matches, null does not have a OneMonth porperty so you will get a null ref exception. You cannot use the ?? operator as it is not OneMonth that is null, it is the result of FirstOrDefault().

To test change your code to

FundPerformance.Where(xx => fund.Id == xx.Id).First().OneMonth ?? -</td>

If you get a "sequence contains no elements" exception instead then you know that is your problem.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top