Reputation: 59
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 ?
Upvotes: 2
Views: 3331
Reputation: 37000
Use this:
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 Tbl_Students { StudentName = s.StudentName, StudentFamily = s.StudentFamily, StudentImage = s.StudentImage, StudentPayeName = p.PayeName, StudentReshtName = r.ReshteName };
return qstudent.ToList();
Select new { ... }
will just create an anonymous type whch can´t be converted to anything except object
.
Just as an aside: you should consider naming your types depending on what an entity is within your application, in your example Student
, not the table where the entity is stored.
Upvotes: 1
Reputation: 2121
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();
}
Upvotes: 1
Reputation: 1820
Instead of an anonymous object use your model class in select
. Then you can return List<StudentModel>
instead of List<object>
.
Upvotes: 0