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???
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With