Home > Blockchain >  How to skip null values and solve error : Value cannot be null
How to skip null values and solve error : Value cannot be null

Time:10-15

How I can solve this error :

 Value cannot be null 

this is the Model :

public class Orders_Tables
{
   // internal IQueryable<object> result { get; set; }
    public Lab_Orders  LabOrders { get; set; }
    public Lab_orders_Cash LabOrdersCash { get; set; }
    public Lab_Sample_status LabOrderStatus { get; set; }

    public IEnumerable<LAB_RESULTS> LabResults { get; set; }

    public IEnumerable<TestsRanges> testsRanges { get; set; }

    public IEnumerable<TestsUnits>  testUnits { get; set; }

    public IEnumerable<LAB_CULTURE_RESULT> LabCultureResults { get; set; }

    public IEnumerable<LAB_MICRO_NEGATIVE_RESULT> LabMicroResults { get; set; }
    public IEnumerable<LabTests> labtests { get; set; }
    public IEnumerable<LAB_RESULTS_CLINIC_VIEW> labClinicsViewResult { get; set; }
    public IEnumerable<LAB_RESULT_CASH_VIEW> labCashView { get; set; }

    public IEnumerable<LAB_PARASITOLOGY_VIEW> LabParasitologyView { get; set; }

    public IEnumerable<LAB_CULTURES_VIEW> LabCulturesView { get; set; }

    public IEnumerable<LAB_MICRO_VIEW> LabMicroView { get; set; }

    public IEnumerable<LAB_HISTOPATHOLOGY_VIEW> LabHistopathologyView { get; set; }

    public IEnumerable<LAB_HISTO_RESULT> LabHistoResult { get; set; }

    public IEnumerable<LAB_PARA_RESULTS> LabParaResult { get; set; }

    public Lab_Hematology_Samples LabSamples { get; set; }

    public IEnumerable<LAB_URINE_ANALYSIS_RESULT> LabUrineResult { get; set; }
    public IEnumerable<LAB_URINE_RESULT_VIEW> LaburineView { get; set; }

  public Patients patients { get; set; }

    public IEnumerable<Customers> customers { get; set; }

}

This is the view I used the Model.order_table :

  @model IEnumerable<AljawdahNewSite.Models.Orders_Tables>
@{
    ViewBag.Title = "Clinics Orders";
    //Layout = "~/Views/Shared/_LayoutPatients.cshtml";
}
<link rel="stylesheet" [email protected]("/Content/bootstrap.min.css")>
<link rel="stylesheet" [email protected]("/Content/style.css")>
     <li><img width="500" height="100" style="margin-left:300px" src="~/Contents/images/mamlakaheader.png" />  <a href="~/Views/Orders/Clinicsorders.cshtml"></a></li>
    <li style="margin-left:1200px"><a [email protected]("Logout", "Login")><span >Logout - تسجيل الخروج </span></a></li>
    <li style="margin-left:500px"> @Html.ActionLink("Welcome "   Session["UserFullname"], "Clinicsorders", "Orders") </li>
    <h3 style="text-align:center;color:coral;padding:10px;margin-left:500px">Orders List</h3>
    


<style> a {color: brown;text-decoration: wavy;text-shadow: 20px;font-size:medium;} a:hover {color: blue;}</style>

@using (Html.BeginForm("Clinicsorders", "Orders", FormMethod.Get))
{ 
    <div >
        <span id="FromDate" style="margin-left:60px;color:red;font-size:large"><b>From Date</b></span><input id="FromDatetext" style="margin-left:10px" type="text" name="startdate" />
        <span id="ToDate" style="margin-left:95px;color:red;font-size:large"><b>To Date</b></span><input id="ToFatetext" type="text" style="margin:10px" name="enddate" /><br /><br />
      <span id="PCfileno" style="color:red;font-size:large"><b>Polyclinic File No</b></span><input id="PCFILENOTEXT" style="margin-left:10px" type="text" name="pcfileno" />
      <span id="IDNO" style="color:red;font-size:large;margin-left:30px"><b>ID or Iqama No</b></span><input id="idnotext" type="text" style="margin:10px" name="idno" />
      <span id="passport" style="color:red;font-size:large"><b>Passport No</b></span><input id="passporttext" style="margin-left:10px" type="text" name="Passport" />
      <span id="mobile" style="color:red;font-size:large;margin-left:30px"><b>Mobile No</b></span><input id="mobiletext" type="text" style="margin:10px" name="Mobile" />
        <input id="Submit1" type="submit" value="Search"  />
    </div>
}
<table >
    <tr>
        <td> Patient Name </td>
        <td> Order No. </td>
        <td> Test Id</td>
        <td> order date    </td>
        <td> Polyclinic File </td>
        <td> Order Status   </td>


    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.patients.Patient_Name</td>
            <td>@item.LabOrders.ORDER_ID</td>
            <!--Here is one-->
            <td>@(item.LabCultureResults?.FirstOrDefault()?.TESTID.HasValue ? item.LabCultureResults?.FirstOrDefault()?.TESTID : "No Test ID" )</td>
            <td>@item.LabOrders.ORDER_DATE</td>
            <td>@item.patients.PCfileNO</td>
            <td>@item.LabOrderStatus.status_name</td>
            <td>@Html.ActionLink("Result", "MasterDetails", new { id = item.LabOrders.ORDER_ID },new { @class = "btn btn-primary" , target = "_blank" })</td>
            <td>@Html.ActionLink("Invoice", "Index", "Invoice", new { id = item.LabOrders.ORDER_ID }, new { @class = "btn btn-primary", target = "_blank" })</td>
            @if (item.LabCultureResults?.FirstOrDefault()?.TESTID)
            {
           <!--Here is two (Do not render if TESTID has not a value)-->
                <td>@Html.ActionLink("Culture Result", "download_culture", new { id = item.LabOrders.ORDER_ID, testid = item.LabCultureResults.FirstOrDefault().TESTID }, new { @class = "btn btn-primary", target = "_blank" })</td>
            }
            @*<td>@Html.ActionLink("Culture Result", "download_culture", new { id = item.LabOrders.ORDER_ID,testid = item.LabCultureResults.FirstOrDefault().TESTID }, new { @class = "btn btn-primary", target = "_blank" })</td>*@
        </tr>

        
        }
</table>

The error appeared on this line when I added TESTID

<td>@item.LabCultureResults.FirstOrDefault().TESTID</td>

How to show TESTID if available and skip if null ?

This is the controller code :

 public ActionResult Clinicsorders(DateTime? startdate,DateTime? enddate, string pcfileno, string idno , string Passport , string Mobile)
        {

            int custId = (int)Session["UserCustid"];
            
            // eager load navigation properties
            // query is IQueryable
            var query = db.Lab_Orders.Where(r => r.CUSTID == custId)
                .Join(db.Lab_Sample_status, order => order.order_status, status => status.status_id, (order, status) => new { Order = order, Status = status })
                .Join(db.Patients, rec => rec.Order.patient_no, patient => patient.Patient_No, (rec, patient) => new Orders_Tables { LabOrders = rec.Order, LabOrderStatus = rec.Status, patients = patient });


            if (startdate.HasValue && enddate.HasValue)
            {
                query = query.Where(r => DbFunctions.TruncateTime(r.LabOrders.ORDER_DATE) >= DbFunctions.TruncateTime(startdate.Value) &&
                    DbFunctions.TruncateTime(r.LabOrders.ORDER_DATE) <= DbFunctions.TruncateTime(enddate.Value));
            }

            if (!string.IsNullOrEmpty(pcfileno))
            {
                query = query.Where(r => r.patients.PCfileNO == pcfileno);
            }

            if (!string.IsNullOrEmpty(idno))
            {
                query = query.Where(r => r.patients.Patient_id == idno);
            }

         
            var model = query.OrderByDescending(r=>r.LabOrders.ORDER_ID).ToList();

            return View(model);
}

I need to make changes on the controller code and add the table , the orders table class include all the tables in one model together

CodePudding user response:

FirstOrDefault returns....default if it does not exist so dereferencing it will generate a nullreference exception

@item.LabCultureResults.FirstOrDefault().TESTID

A quick fix is to use the null coalescent operator ( ? )

@item.LabCultureResults.FirstOrDefault()?.TESTID

OR

@item.LabCultureResults.FirstOrDefault() ?? "EMPTY"

CodePudding user response:

I catch another issue in your code. You have two accessors in page for TESTID. They marked on code below. You have to handle both accessors. May be your item or LabOrdersis null. If not, the code below can does the job.

If condition depends on its own type.

For example if TESTID is int? you can use this:

item.LabCultureResults?.FirstOrDefault()?.TESTID.HasValue

<table >
    <tr>
        <td> Patient Name </td>
        <td> Order No. </td>
        <td> Test Id</td>
        <td> order date    </td>
        <td> Polyclinic File </td>
        <td> Order Status   </td>


    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.patients.Patient_Name</td>
            <td>@item.LabOrders.ORDER_ID</td>
            <!--Here is one-->
            <td>@(item.LabCultureResults?.FirstOrDefault()?.TESTID.HasValue ? item.LabCultureResults?.FirstOrDefault()?.TESTID : "No Test ID" )</td>
            <td>@item.LabOrders.ORDER_DATE</td>
            <td>@item.patients.PCfileNO</td>
            <td>@item.LabOrderStatus.status_name</td>
            <td>@Html.ActionLink("Result", "MasterDetails", new { id = item.LabOrders.ORDER_ID },new { @class = "btn btn-primary" , target = "_blank" })</td>
            <td>@Html.ActionLink("Invoice", "Index", "Invoice", new { id = item.LabOrders.ORDER_ID }, new { @class = "btn btn-primary", target = "_blank" })</td>
            @if(item.LabCultureResults?.FirstOrDefault()?.TESTID.HasValue) 
            {
           <!--Here is two (Do not render if TESTID has not a value)-->
           <td>@Html.ActionLink("Culture Result", "download_culture", new { id = item.LabOrders.ORDER_ID,testid = item.LabCultureResults.FirstOrDefault().TESTID }, new { @class = "btn btn-primary", target = "_blank" })</td>
            }
       </tr>
</table>

CodePudding user response:

A combination of the above answers:

Try: @item?.LabCultureResults.FirstOrDefault()?.TESTID ?? ""

CodePudding user response:

Sample code demonstrating the problem:

List<string> LabCultureResults = null;

Console.WriteLine(LabCultureResults.Count); // (1)
Console.WriteLine(LabCultureResults.FirstOrDefault()); // (2)

(1) throws the infamous NullReferenceException ("Object reference not set to an instance of an object.").

(2) throws an ArgumentNullException with message "Value cannot be null. (Parameter 'source')", because an extension method (like FirstOrDefault) can be called on a null value, but may decide not to accept it.

So your LabCultureResults is null.

When that Model is the result of an Entity Framework query, you need to .Include(it => it.LabCultureResults).

Be aware that FirstOrDefault() may return a null, so don't just get the TESTID of the result - that will throw a NullReferenceException when the result is null. So use item.LabCultureResults?.FirstOrDefault()?.TESTID.

  • Related