I am working on Web Api where I would have to create Data Transfer Objects for displaying data on the UI of application.
I am working with Code First approach here is my Domain class
public class Employee
{
[Key]
public int BusinessEntityId { get; set; }
[Required]
[MaxLength(50)]
public string JobTitle { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime BirthDate { get; set; }
[Required]
[MaxLength(1)]
public string MaritalStatus { get; set; }
[Required]
[MaxLength(1)]
public string Gender { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime HireDate { get; set; }
[Required]
public Boolean SalariedFlag { get; set; }
public ICollection<EmployeePayHistory> PayHistories { get; set; }
}
Here is my Data Transfer Object(DTO) Class
public class EmployeePayHistoryListDTO
{
public int Id { get; set; }
public DateTime RateChangeDate { get; set; }
public Decimal Rate { get; set; }
public Int16 PayFrequency { get; set; }
public String JobTitle { get; set; }
public String Gendre { get; set; }
}
Now As PayHistories is collection in my Domain class I what i am doing is i am creating a new class
of which has collection of my DTO class type EmployeePayHistoryListDTO
public class EmployeeRelatedCollections
{
public ICollection<EmployeePayHistoryListDTO> PayHistories { get; set; }
}
So from my repository I am getting data correctly via following EF statement
_context.Employees.Include("PayHistories")
.Include("PayHistories")
.Single(e=>e.BusinessEntityId==id);
But where i am converting collection of my Employee class(Domain Class) to collection of my DTO type there i am getting error here is the code
PayHistories = (from ph in employee.PayHistories
select new EmployeePayHistoryListDTO
{
Id = ph.BusinessEntityId,
RateChangeDate = ph.RateChangeDate,
Rate = ph.Rate,
PayFrequency = ph.PayFrequency,
JobTitle = ph.Employee.JobTitle,
Gendre = ph.Employee.Gender
}).ToList();
I am getting following exception below is summary
System.NullReferenceException ,
Additional Information: Object reference Not set to an instance of an object.
Troubleshooting tips
1. Check to determine if the object is null before calling the method,
2. Use new keyword to create an object instance.