【发布时间】:2014-09-03 13:53:15
【问题描述】:
我正在开发 Web Api,我必须创建数据传输对象以在应用程序的 UI 上显示数据。
我正在使用 Code First 方法,这是我的域类
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; }
}
这是我的数据传输对象 (DTO) 类
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; }
}
现在,由于 PayHistories 是我的域类中的集合,我正在做的是创建一个新类
其中集合了我的 DTO 类类型EmployeePayHistoryListDTO
public class EmployeeRelatedCollections
{
public ICollection<EmployeePayHistoryListDTO> PayHistories { get; set; }
}
所以我通过以下 EF 语句从我的存储库中正确获取数据
_context.Employees.Include("PayHistories")
.Include("PayHistories")
.Single(e=>e.BusinessEntityId==id);
但是我在将我的 Employee 类(域类)的集合转换为我的 DTO 类型的集合的地方出现错误,这里是代码
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.
【问题讨论】:
-
我认为您错过了错误粘贴:P
-
是的,非常感谢,我现在再次编辑它,请再看一遍。
-
空引用发生在哪里?
标签: c# linq entity-framework dto