2016-11-13 46 views
1

我需要將Linq加入4個tabel。但它表明我這個錯誤:無法在asp mvc中隱式轉換類型'System.Collections.Generic.List

錯誤1無法隱式轉換類型 'System.Collections.Generic.List <>' 到 'System.Collections.Generic.List' E:\ MyProject的\ GoKhoda \ GoKhoda \地區\類\ StudentsFunc.cs 20 20 GoKhoda

這是我的代碼:

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

爲什麼顯示我的錯誤?我該如何解決這個問題?

+0

這個異常沒有告訴我們可以告訴你的那麼多。 –

回答

1

問題它的匿名類型是從您的LINQ查詢的返回類型。這個匿名類型是由編譯器根據select new {}語句中指定的名稱和類型定義的。

要解決它,你可以定義一個新類型的學生

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

,然後在LINQ的select語句和返回類型爲ShowAllStudents方法

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

使用此:

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 { ... }將只創建一個匿名類型界河不容轉換爲什麼除了object

正如一邊:學生,而不是存儲實體的表格。

0

,而不是一個匿名使用學生類型對象在select中使用您的模型類。然後您可以返回List<StudentModel>而不是List<object>

相關問題