dotnetdevcsharp
dotnetdevcsharp

Reputation: 3980

.net linq winforms cannot convert anonymous type

Hi I am trying to do a join on the two tables below but for some reason I am getting an error

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();

I get the error cannot convert anonymous type I'm quite new to LINQ so not sure why this error would occur.

sorry guys this is what i have tired i had to modify query for telrik reporting so that i had the description in the join so can display it on a report

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;
    }

this is the sql query i am trying to duplicate

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

that is what

Upvotes: 1

Views: 89

Answers (1)

Jon
Jon

Reputation: 437336

Your code projects the results into a sequence of anonymous type instances new { a, b }, and you are trying to use that list as a list of something else. Project the results into the proper named type instead.

For example, one solution might be

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();

This will get you a list of Tuple<T1, T2> where T1 is the type of a and T2 is the type of b. You can of course create your own custom type instead:

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

and use it as in

select new MyType { Appraisal = a, Readiness = b }

Upvotes: 2

Related Questions