2013-04-03 91 views
1

這是我使用的通用respoitory,作爲標題說明我想知道如何過濾導航屬性。通用知識庫:如何過濾急切加載的導航屬性

public IEnumerable<T> Query(
     Expression<Func<T, bool>> filter = null, 
     Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, 
     string includeProperties = "") 
    { 
     IQueryable<T> query = _objectSet.Where(e => !e.IsDeleted);    

     if (filter != null) 
     { 
      query = query.Where(filter); 
     } 

     foreach (var includeProperty in includeProperties.Split 
      (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) 
     { 
      query = query.Include(includeProperty); 
     } 

     if (orderBy != null) 
     { 
      return orderBy(query).ToList(); 
     } 
     else 
     { 
      return query.ToList(); 
     } 
    } 

控制器:

var viewModel = new StudentViewModel(); 
     viewModel.Students= _unitOfWork.Students.Query(
      includeProperties: "Subjects, Instructors"); 

現在我的問題是我想補充一個。凡(E => e.IsDeleted!) 使用存儲庫[主題]和[教師。

感謝

編輯: 根據拉吉斯拉夫,目前這是不可能的(也是在MSDN這裏提到:http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx

Can i just use this instead? 
viewModel.Subjects = viewModel.Students.Where(i => i.StudentID ==Id.Value) 
        .Single().Subjects.Where(e => !e.IsDeleted); 

我唯一擔心的是,查詢可返回大量記錄==請將isDeleted真實。確定我發佈的代碼作爲替代作品,我只是不想提取我不需要的數據,即使我可以使用上面的代碼進行過濾

+0

你能否解釋一下你的意思是「使用存儲庫向[主體]和[教師]添加一個.Where(e =>!e.IsDeleted)」。 – Alex

+0

@voo我想她想過濾包含的屬性。 – tschmit007

+0

@ samantha07你能告訴我們query.Include()方法嗎? – Alex

回答

2

LINQ to SQL支持使用LoadWith DataLoadOption 。在http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.loadwith.aspx的例子顯示了EF用Include語句支持的簡單情況。

Northwnd db = new Northwnd(@"c:\northwnd.mdf"); 
DataLoadOptions dlo = new DataLoadOptions(); 
dlo.LoadWith<Customer>(c => c.Orders); 
db.LoadOptions = dlo; 

然而,與EF,LINQ to SQL中還支持以下內容:

dlo.LoadWith<Customer>(c => c.Orders.Where(o => o.ShippedDate is Null); 

如果你覺得這是EF最重要的增強的情況下,考慮在http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1015345-allow-filtering-for-include-extension-method爲它投票。

現在,您最好的選擇是將您的過濾器投影到Select子句中,但是對於通用存儲庫來說,這會變得棘手。