LINQ to Entities无法识别方法' System.Collections.Generic.Dictionary`2 [System.Int32,System.String] ToDictionary

时间:2014-09-18 22:54:01

标签: c# linq entity-framework

我正在尝试从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?

由于

1 个答案:

答案 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;
    });