views:

81

answers:

2

Hello,

I have a strange behavior. The code below worked from a long time but nowI don't know why I didn't change anything, I have an exception. I get employee from my database via Nhibernate, the _model.List have the employee list. I have an exception on the line juste before the return (where I build the array). I format the data to use them in jqGrid.

The exception is : Object reference not set to an instance of an object.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ListToGrid(string sidx, string sord, int page, int rows)
{
    _model.List = _employeeService.List();

    Func<Employee, string> order;
    switch (sidx.ToUpper())
    {
        case "FIRSTNAME": order = x => x.FirstName; break;
        case "LASTNAME": order = x => x.LastName; break;
        default: order = x => x.Login; break;
    }

    if (sord.ToUpper() == "ASC")
        _model.List = _model.List.OrderBy(order).ToList<Employee>();
    else
        _model.List = _model.List.OrderByDescending(order).ToList<Employee>();

    var data = _model.List.Select(c => new { id = c.Id, cell = new[] { c.Id.ToString(), c.Login.ToString(), c.FirstName, c.LastName, c.IsActive.ToString() } }).ToArray();
    return new JsonResult { Data = new { page = page, records = data.Length, rows = data, total = 1 } };            
}
+4  A: 

So you're saying that this line

var data = _model.List.Select(c => new { id = c.Id, cell = new[] { 
    c.Id.ToString(),
    c.Login.ToString(),
    c.FirstName,
    c.LastName,
    c.IsActive.ToString()
} }).ToArray();

throws an exception. Then, it would appear quite likely either c.Id, c.Login or c.IsActive is null for at least one c in _model.List as these are the only properties of c for which a dereference is necessary. Those are your main culprits so start checking your data.

Jason
Haaaaa you are right ! how can I manage this because some field can be null ....
Kris-I
.Where(c => c != null).Select()
Andreas Niedermair
Well, the straightforward approach is to, say, replace `c.Id.ToString()` by `c.Id == null ? String.Empty : c.Id.ToString()` and repeat for each of the possibly-null properties. Of course, you can consider factoring this logic into a method.
Jason
@dittodhole: No, that eliminates the `c` where `c` is null and doesn't deal at all with the `c` where `c.Id` or `c.Login` or `c.IsActive` is `null`. Moreover, the OP doesn't want to filter those `c` out as he permits the possibility of them being `null`.
Jason
+1  A: 

In all likelihood, you have a row in your database with Id, Login or IsActive set to null. Can you post the entire stacktrace for more info?

NickLarsen