.net linq winforms无法转换匿名类型

时间:2013-08-09 08:27:53

标签: .net sql winforms

您好我正在尝试在下面的两个表上进行联接但由于某种原因我收到错误

var query = (from a in pamsEntities.appraisals
             where a.emp_no == employeeId
             join b in pamsEntities.AppraisalReadinesses on a.AppraisalReadiness.Code equals b.Code
             select new { a, b }).ToList();

我收到错误无法转换匿名类型我对LINQ很新,所以不确定为什么会出现此错误。

抱歉,这是我累了,我不得不修改telrik报告的查询,以便我在连接中有描述,所以可以在报告上显示

public List<appraisal> GetAppraisal(int employeeId)
    {
        List<appraisal> Appraisals = new List<appraisal>();

        try
        {

           var query = (from a in pamsEntities.appraisals
                         where a.emp_no == employeeId
                         join b in pamsEntities.AppraisalReadinesses on a.AppraisalReadiness.Code equals b.Code
                          select Tuple.Create(a, b)).ToList();
           Appraisals = query;//pamsEntities.appraisals.Where(a => a.emp_no == employeeId).ToList();
        }
        catch (Exception ex)
        {
            throw new EntityContextException("GetAppraisal failed.", ex);
        }


        return Appraisals;
    }

这是我试图复制的SQL查询

select a.*, b.*
from appraisls a , AppraisalReadiness b
where a.Readiness = b.code
and a.emp_no = emp_code;

where empcode is just a vairable

这就是

1 个答案:

答案 0 :(得分:2)

您的代码将结果投影到一系列匿名类型实例new { a, b }中,并且您尝试将该列表用作其他内容的列表。将结果投影到适当的命名类型中。

例如,一个解决方案可能是

var query = (from a in pamsEntities.appraisals
             where a.emp_no == employeeId
             join b in pamsEntities.AppraisalReadinesses 
             on a.AppraisalReadiness.Code equals b.Code
             select Tuple.Create(a, b)).ToList();

这会为您提供Tuple<T1, T2>的列表,其中T1的类型为aT2的类型为b。您当然可以创建自己的自定义类型:

class MyType
{
    // I am guessing about the type names here, based on your query
    Appraisal Appraisal; { get; set; }
    AppraisalReadiness Readiness; { get; set; }
}

并在

中使用它
select new MyType { Appraisal = a, Readiness = b }