当客户名称或代理商名称=空时,我收到错误

时间:2016-06-16 17:20:23

标签: asp.net-mvc-5 nullable

当客户名称或代理商名称=空

时出错
 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);

3 个答案:

答案 0 :(得分:0)

如果您的意思是引用了引用错误,因为代理和客户未在用户类的构造函数中加载,则必须使用延迟加载

Public class user{
public user
(
agent=new Agent();
customer=new Customer();
)

}

答案 1 :(得分:0)

您收到错误,因为您正在尝试访问Null对象的属性。在这种情况下,代理和客户属性。在尝试使用它们之前,您需要测试空值。

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);

或者,如果您使用的是C#6,则可以使用新的简写

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);

答案 2 :(得分:0)

我使用此代码并且工作了 谢谢

var results = db.Users.Include("Customer").Include("Agent").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);