I Love Stackoverflow
I Love Stackoverflow

Reputation: 6868

How to avoid Object reference not set to instance of object error with FirstOrDefault?

This is my class:

public class Employee
{
     public int EmployeeId { get; set; }
     public int Skillssetpoints { get; set; }
     public string Name { get; set; }
     public string EmployeeCode { get; set; }
     public Nullable<System.DateTime> Date { get; set; }
}

Code:

Scenario 1:

var data=context.Employee.ToList();  //Get all employee records.

//Filter records by employee code(Emp01) and fetch single employee code.for eg:Emp01

var empCode = data.FirstOrDefault(t =>(t.EmployeeCode.Trim() == Model.EmployeeCode.Trim())).EmployeeCode;

Here if there is no match found with Emp01 then getting error object reference not set to instance of object but fixed this with below code:

var Single = data.FirstOrDefault(t =>(t.EmployeeCode.Trim() == Model.EmployeeCode.Trim()));

if(single!=null)
{
   var data=Single.EmployeeCode;
   //Rest other code.
}

Scenario 2:

var data=context.Employee.ToList();  //Get all employee records.

//Fetch List of employee with Employee code:Emp01

var list= data.FirstOrDefault(t =>(t.EmployeeCode.Trim() == Model.EmployeeCode.Trim()));

Here in my data object if any EmployeeCode is null then i am getting this error:

Error:object reference not set to instance of object

Fixed with this:

var list= data.FirstOrDefault(t => (t.EmployeeCode != null) && (t.EmployeeCode.Trim() == Model.EmployeeCode.Trim()));

For my second scenario when i was fetching all the records of employee and doing filter by Employee code i havent addedd this null condition at first because i was having all employee records wihtout any null employee code and everything was working fine but at any point employee code became null and got this error.so in future i want to avoid this mistakes.

So i just want to know that is there any better way to handle both this scenario???

Upvotes: 4

Views: 3758

Answers (2)

Palanikumar
Palanikumar

Reputation: 7150

var employees = context.Employee.ToList();
var result = employees.Where(t => (t.EmployeeCode ?? "").Trim() == (Model.EmployeeCode ?? "").Trim())
                    .Select(t => t.EmployeeCode).FirstOrDefault();

Upvotes: 1

Rob
Rob

Reputation: 27357

For scenario 1, you can write something like this:

var employees = context.Employee.ToList();
var data = employees.Where(t => t.EmployeeCode.Trim() == Model.EmployeeCode.Trim())
                    .Select(t => t.EmployeeCode)
                    .FirstOrDefault();

if(data != null)
{
   //Rest other code.
}

For scenario 2, you can add an extra where to filter out nulls. However way you slice it, you will need to check, but splitting up the filtering is nicer, at least in my opinion:

var list= data
          .Where(d => d != null)
          .FirstOrDefault(t => t.EmployeeCode.Trim() == Model.EmployeeCode.Trim());

Upvotes: 4

Related Questions