0

目前我正面临嵌套 linq 的问题。

这是我的表格,现在我正在开发 MVC4 Razor Web 应用程序。

student
student_id,studentname,description
book
book_id,student_id,bookname,checkitout
booker
bookerid,book_id,bookername,bookerdescription

我创建了用于显示的模型

public class student_model{
    public int student_id {get;set;}
    public string studentname {get;set;}
    public string bookname {get;set;}
}

大家好,这里是我的表格,现在我正在开发 MVC4 Razor Web 应用程序。我想为 booker 编写嵌套的 LINQ。所以我使用以下 LINQ:

public List<student_model> finder (int stuid){
    var stubk = (from stu in contx.students
        join bk in contx.books on stu.student_id equals bk.student_id
        where stu.student_id == stuid
        select new {
            //here is wrong
            student = from bker in contx.bookers
                where bker.book_id=bk.book_id
                select new student_model{
                    student_id = stu.student_id,
                    studentname = stu.studentname,
                    bookname = bk.bookname
                }   
        }).ToList();

    var next = stubk.Select(md=>md.student)

    return (List<student_model>) next;
}   

这是错误的嵌套 LINQ。那么我该怎么做才能制作过滤器bookers.book_id = bk.book_id呢?我应该如何返回(List<student_model)?

谢谢青蛙

4

2 回答 2

1

我认为您根本不需要为此使用 Bookers 课程。

此答案假定由于您使用的是实体框架,因此您在这些类上具有指向彼此的导航属性(即 Books 在其类上具有 Student 的属性,而 Student 在其类上具有 Books 的集合)。

使用 LINQ 扩展方法,您可以执行以下操作:

var studentModelList = new List<student_model> ();
contx.Students.Include("Books")
              .Where(stu => stu.student_id == stuid)
              .Select(stu => stu.Books).ToList()
              .ForEach(bookObj => 
                      studentModelList.Add(new student_model { student_id = bookObj.student.student_id, studentname = bookObj.student.studentname, bookname = bookObj.bookname}))
return studentModelList;
于 2013-01-07T03:53:32.497 回答
0

删除嵌套并添加额外的连接

public List<student_model> finder (int stuid){
    var stubk = (from stu in contx.students
        join bk in contx.books on stu.student_id equals bk.student_id
        join bker in contx.bookers on bk.book_id equals bker.book_id
        where stu.student_id == stuid && bker.book_id=bk.book_id
                select new student_model{
                    student_id = stu.student_id,
                    studentname = stu.studentname,
                    bookname = bk.bookname
                }).ToList();
于 2013-01-07T03:53:15.850 回答