LINQ to Entities不识别方法';System.Collections.Generic.Diction

本文关键字:System Collections Generic Diction Entities to 识别 方法 LINQ | 更新日期: 2023-09-27 18:22:39

我正在尝试从存储在Employee表中的DB中检索EmployeeDTO的列表。每个员工都可以有一个或多个专业。专业存储在OrganizationSpecialtyType中。EmployeeOrganizationSpecialtyType通过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,
                                        Specialty = p.EmployeeSpecialty
                                                            .ToDictionary(d => d.OrganizationSpecialtyType.SpecialtyTypeID, d => d.OrganizationSpecialtyType.Name)
                                    }
                        );

EmployeeDTO类中,属性Specialty是类型public Dictionary<int, string>

如果我执行这个查询,一切正常:

var spec = _context.Employee.Where(p => p.EmployeeID == -9070).FirstOrDefault()
    .EmployeeSpecialty.ToDictionary(d =>
         d.OrganizationSpecialtyType.SpecialtyTypeID,
         d => d.OrganizationSpecialtyType.Name);

如何解决我的第一个查询以获得具有专业知识的EmployeeDTO

谢谢。

LINQ to Entities不识别方法';System.Collections.Generic.Diction

您可以先选择匿名类型,然后再设置字典。

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;
    });
相关文章: