不能隐式转换类型'System.Collections.Generic.列表在asp mvc

本文关键字:Generic Collections 列表 mvc asp System 转换 类型 不能 | 更新日期: 2023-09-27 18:17:36

我需要与Linq连接4表。但是它显示了这个错误:

错误1无法隐式转换类型'System.Collections.Generic. list <>到'System.Collections.Generic. list <>List' E:'MyProject'GoKhoda'GoKhoda'Areas'Classes' studentsfunction .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();
    }

为什么显示错误?我该如何解决这个问题?

不能隐式转换类型'System.Collections.Generic.列表在asp mvc

使用

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

作为题外话:你应该考虑根据你的应用程序中的实体来命名你的类型,在你的例子中是Student,而不是存储实体的表。

问题在于匿名类型是LINQ查询的返回类型。此匿名类型由编译器根据select new{}语句中指定的名称和类型定义。

要解决这个问题,可以定义一个新的类型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; }
}

,然后在LINQ的select语句中使用Student类型,并作为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();
}

select中使用您的模型类而不是匿名对象。然后您可以返回List<StudentModel>而不是List<object>

相关文章: