Home > Back-end >  How can I resolve my null error coming to @role.Name below?
How can I resolve my null error coming to @role.Name below?

Time:10-14

@foreach (var a in Model.USERS.OrderBy(p => p.NAMESURNAME))
{
    var role = Model.ROLLER.FirstOrDefault(p => p.ID == a.ROLID);
    <tr id="tr@(a.ID)">
        <td>@a.NAMESURNAME</td>
        <td>@a.USERNAME</td>
        <td style="width:120px">@a.GOREV</td>
        <td>@a.EMAIL</td>
        <td>@a.PHONENUMBER</td>
        <td>@role.NAME</td>
        <td>@a.VERSİON</td>
        <td>
            <a asp-action="AddUser" asp-route-userId="@a.ID" data-container="body" data-toggle="m-popover" data-placement="top" data-content="Edit"><i ></i></a>
            <a  data-id="@a.ID" data-id2="@a.NAMESURNAME" data-container="body" data-toggle="m-popover" data-placement="top" data-content="Delete"><i ></i></a>
        </td>
    </tr>
}

I get the following error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

role was null.

CodePudding user response:

The FirstOrDefault() method returns the first element of a sequence, or a default value if no element is found. The default value for reference and nullable types is null.

Therefore, it is necessary to use Null-conditional operators ?. to prevent the System.NullReferenceException exception:

<td>@role?.NAME</td>
  • Related