我正在尝试从DB中检索EmployeeDTO列表,这些列表存储在Employee表中。每个员工都可以拥有一个或多个专业。专业存储在OrganizationSpecialtyType中。 Employee和OrganizationSpecialtyType与"多对多"通过EmployeeSpecialty表。
我使用以下查询,并在标题中得到异常:
var q = _context.Employee.Where(p => employeeEMIIDs.Contains(p.EmployeeID))
.Select(p => new EmployeeDTO
{
EmployeeID = p.EmployeeID,
GenderTypeID = p.GenderTypeID,
FirstName = p.FirstName,
LastName = p.LastName,
Name = p.Name,
MiddleName = p.MiddleName,
DOB = p.DOB,
Suffix = p.Suffix,
Title = p.Title,
Sepcialty = p.EmployeeSpecialty
.ToDictionary(d => d.OrganizationSpecialtyType.SpecialtyTypeID, d => d.OrganizationSpecialtyType.Name)
}
);
在EmployeeDTO类属性中,特性是类型公共字典。
如果我执行此查询,一切都正常:
var spec = _context.Employee.Where(p => p.EmployeeID == -9070).FirstOrDefault().EmployeeSpecialty.ToDictionary(d => d.OrganizationSpecialtyType.SpecialtyTypeID, d => d.OrganizationSpecialtyType.Name);
如何解决我的第一个查询以获得具有专业的EmployeeDTO?
由于
答案 0 :(得分:7)
您可以先选择匿名类型,然后再设置字典。
var q = _context.Employee.Where(p => employeeEMIIDs.Contains(p.EmployeeID))
.Select(p => new
{
Employee = new EmployeeDTO
{
EmployeeID = p.EmployeeID,
GenderTypeID = p.GenderTypeID,
FirstName = p.FirstName,
LastName = p.LastName,
Name = p.Name,
MiddleName = p.MiddleName,
DOB = p.DOB,
Suffix = p.Suffix,
Title = p.Title
},
Specialty = p.EmployeeSpecialty
.Select(d => new
{
d.OrganizationSpecialtyType.SpecialtyTypeID,
d.OrganizationSpecialtyType.Name
})
})
.AsEnumerable()
.Select(a =>
{
a.Employee.Specialty = a.Specialty
.ToDictionary(d => d.SpecialtyTypeID, d => d.Name);
return a.Employee;
});