Hi @anil kumar ,
If one of the tables has no record, the joined table is empty, then when you access the joined table property in the where
clause or the select
clause, it will show the NullReferenceException.
To solve this exception, you could check whether the joined table exist or not in the where
clause and select
clause, please refer the following sample code:
var employees = _repository.GetEmps();//get all emps
var empAttendances = _repository.GetAttendances();//get all attendances
var offMas = _repository.GetOffMas();
//define a variable to store the return data. It can prevent the NullReferenceException when returns null to the view page.
var empRecord = new List<EmpAttendanceViewModel>();
var filterresult = (from e in employees
join d in empAttendances on e.AId equals d.EmpAId into table1
from t1 in table1.ToList().DefaultIfEmpty()
join i in offMas on e.OffMasId equals i.Id into table2
from t2 in table2.ToList().DefaultIfEmpty()
where t2?.AId == 1 //if t2 contains value, apply the filter.
select new EmpAttendanceViewModel
{
AId = e.AId,
EmpId = e.Empid,
Name = e.name,
offid = t1?.EmpAId ?? 0, // use '?' to check if the table is empty or not, if the table is empty set the default value.
Time = ((t1?.TOut ?? new TimeSpan(0, 0, 0)) - (t1?.TIn ?? new TimeSpan(0, 0, 0))).ToString(),//(t1.TOut - t1.TIn).ToString() //
}).ToList();
//add the filter result to the return list.
empRecord.AddRange(filterresult);
The result as below:
The empAttendances
and offMas
has no data:
The empAttendances
has no data:
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion