Kianoush Kianoush - 25 days ago 7
C# Question

Cannot implicitly convert type 'System.Collections.Generic.List in asp mvc

i need join 4 tabel with Linq . but it show me this error :


Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<>' to 'System.Collections.Generic.List' E:\MyProject\GoKhoda\GoKhoda\Areas\Classes\StudentsFunc.cs 20 20 GoKhoda


this is my code :

public List<Tbl_Students> ShowAllStudents()
{
var qstudent = from s in _db.Tbl_Students
join pr in _db.Tbl_Pye_Reshte on s.StudentID equals pr.StudentID
join r in _db.Tbl_Reshte on pr.ReshteID equals r.ReshteID
join p in _db.Tbl_Paye on pr.PayeID equals p.PayeID
orderby p.PayeID descending
select new { StudentName = s.StudentName, StudentFamily = s.StudentFamily, StudentImage = s.StudentImage, StudentPayeName = p.PayeName, StudentReshtName = r.ReshteName };
return qstudent.ToList();
}


Why Show Me Error ? How can i solve this ?

Answer

The issue it that anonymous type is a return type from your LINQ query. This anonymous type is defined by compiler based on the names and types specified in the select new {} statement.

To fix it, you can define a new type Student

public class Student
{
    public string StudentName { get; set; }
    public string StudentFamily { get; set; }
    public byte[] StudentImage { get; set; }
    public string StudentPayeName { get; set; }
    public string StudentReshtName { get; set; }
}

and then use Student type in LINQ's select statement and as return type for the ShowAllStudents method

public List<Student> ShowAllStudents()
{
    var qstudent = from s in _db.Tbl_Students
                   join pr in _db.Tbl_Pye_Reshte on s.StudentID equals pr.StudentID
                   join r in _db.Tbl_Reshte on pr.ReshteID equals r.ReshteID
                   join p in _db.Tbl_Paye on pr.PayeID equals p.PayeID
                   orderby p.PayeID descending
                   select new Student { StudentName = s.StudentName, StudentFamily = s.StudentFamily, StudentImage = s.StudentImage, StudentPayeName = p.PayeName, StudentReshtName = r.ReshteName };
    return qstudent.ToList();
}