2013-01-07 128 views
0

目前我正面臨嵌套LINQ的問題。MVC4中的嵌套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剃刀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)?

感謝 青蛙

回答

1

我不認爲你需要在所有使用的預訂者類此。

這個答案假設你既然使用了實體框架,那麼你在那些指向對方的類上有導航屬性(例如,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; 
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();