Search code examples
asp.net-mvc-5nullable

i got error When Customer Name or Agent Name = Null


and i got error When Customer Name or Agent Name = Null

 var results = db.Users.ToDataSourceResult(request, o => new
            {
                Id= o.Id,
                UserName = o.UserName,
                Email = o.Email,
                PhoneNumber = o.PhoneNumber,
                AgentName = o.Agent.FullName,
                CustomrName = o.Customer.Name 


            });

            return Json(results, JsonRequestBehavior.AllowGet);

Solution

  • You are getting an error because you are attempting to access the property of an object that is Null. The Agent and Customer properties in this case. You need to test for nulls before attempting to use them.

    var results = db.Users.ToDataSourceResult(request, o => new
    {
        Id = o.Id,
        UserName = o.UserName,
        Email = o.Email,
        PhoneNumber = o.PhoneNumber,
        AgentName = o.Agent == null ? null : o.Agent.FullName,
        CustomrName = o.Customer == null ? null : o.Customer.Name
    });
    
    return Json(results, JsonRequestBehavior.AllowGet);
    

    Or if you are using C# 6 you can use the new shorthand

    var results = db.Users.ToDataSourceResult(request, o => new
    {
        Id = o.Id,
        UserName = o.UserName,
        Email = o.Email,
        PhoneNumber = o.PhoneNumber,
        AgentName = o.Agent?.FullName,
        CustomrName = o.Customer?.Name
    });
    
    return Json(results, JsonRequestBehavior.AllowGet);