Austin
Austin

Reputation: 3080

Linq Queryable missing a cast?

I am trying to grab data from three tables, however I am getting an error on the final join statement and I am not sure why.

Everything DID work fine when I had a single select e.Name; but once I added more variables it started having this error problem.

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?)

public ActionResult EmployeeInfo()
        {
        var emp = db.Employees;
    var mov = db.Movies;
    var moveemp = db.MovieEmployees;

    IQueryable<string> query =
    from m in db.Movies

    join me in db.MovieEmployees 
    on m.ID equals me.movieID

    join e in db.Employees
    on me.employeeID equals e.ID



    // this join gives the error
    join r in db.Roles
    on me.roleID equals r.ID

    select new { e.Name, r.RoleType, e.Birthday, m.ID };

    return View(query.Distinct().ToList());
}

Thank you!

Upvotes: 1

Views: 1014

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

You are defining query variable or type IQueryable<string>. But your query returns anonymous objects (i.e. it has type of IQueryable<anonymous_type>). Of course it's not possible to assign such query to your query variable. Create view model type:

public class EmployeeInfoViewModel
{
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
    public int ID { get; set; }
    // RoleType, etc
}

Use it as model for your view:

@model IEnumerable<EmployeeInfoViewModel>

and pass list of this view models to your view (don't forget to use var keyword when define query - type of query will be inferred from query definition):

var query = ....
            select new { e.Name, r.RoleType, e.Birthday, m.ID };

var model = query.Distinct()
                 .Select(x => new EmployeeInfoViewModel {
                      Name = x.Name,
                      Birthday = x.Birthday,
                      ID = x.ID
                  }).ToList();

return View(model);

Upvotes: 1

Related Questions