2012-02-20 27 views
4

使用MVC3,我有一個Student Repository(在一個項目中)和一個StudentService(在另一個項目中)。在服務中,我想創建一個返回db表中所有學生的函數。這是一種爲我做事情的新方式,所以我有點新。在下面的GetAllStudents函數中,我如何更改語法來選擇全部。如何選擇全部使用IQueryable

在存儲庫:

 namespace SpeakOut.Data 
{ 
    public class StudentRepository 
{ 
    SpeakOutDataContext context; 
    private Table<StudentEntity> table; 
    public StudentRepository() 
    { 
     context = new SpeakOutDataContext(); 
     table = context.GetTable<StudentEntity>(); 
    } 


    public IQueryable<Student> Select() 
    { 
     return table.Select(x => new Student 
           { 
            WNumber = x.WNumber, 
            CatalogueYear = x.CatalogueYear, 
            Standing = x.Standing 
           }); 
    } 
} 

}

在服務:

namespace SpeakOut.Services 
    { 
    public class StudentService 
{ 
    private StudentRepository repository; 
    public StudentService() 
    { 
     repository = new StudentRepository(); 

    } 

    public IQueryable<Student> GetAllStudents() 
    { 
     return repository.Select().All(x => x.FirstName) ; //**This line is where I don't know how I would call all the students** 
    } 


} 

}

+1

哦,等等爲什麼我不能說只是返回repositry.Select() – TMan 2012-02-20 17:06:12

回答

2
public IQueryable<Student> GetAllStudents() 
{ 
    return repository.Select(); 
} 

以上只是一個直通方法的代碼。唯一的好處是隱藏服務器後面的存儲庫,或者給它一個更好的名字。

此時尚未檢索到任何數據。例如,當調用.ToList()時,數據收集被推遲到IQuerable被使用。把它作爲IQuerablye的好處是可以通過代碼進一步添加額外的過濾器和排序順序。這些添加將被LINQ提供商使用。

+0

哈哈是啊我想在這一個努力..我是一個虛擬。謝謝! – TMan 2012-02-20 17:07:15

2

你甚至不需要只是一個空白選擇,你可以調用.AsQueryable,或只是返回'表'作爲IQueryable。