2011-11-07 94 views
2

Iam已經遇到了部分投影的小問題。NHibernate Linq選擇投影 - 用局部選擇檢索完整實體

我在我們的列表框中有一個方法,以便我們可以輕鬆地將實體加載到它們中,但是加載完整實體當然不是一個選項。 含義我必須做一些投影,我已經在這裏做了這個,你可以選擇哪個屬性作爲DisplayValue。

使用代碼如下所示:

實施
dropCompany.LoadEntityList(Customer.Company, x => x.CompanyName, x => x.IsCompany); 

部分看起來是這樣的:

public void LoadEntityList<T>(T selectedEntity, 
           System.Linq.Expressions.Expression<Func<T, string>> selector, 
           System.Linq.Expressions.Expression<Func<T,bool>> where = null) 
    where T : FlexyBook.Infrastructure.Entity 
{ 
    var wCollection = new ObjectWrapperCollection<object>(); 
    IQueryable<T> query = FlexyBook.Repository.DomainService<T>.GetDomainService().GetAll(); 
    if (where != null) 
     query = query.Where(where); 
    foreach (var item in query.Select(x => 
     new ObjectWrapper<object>() 
     { 
      Value = x.ID, 
      Text = selector.Compile()(x) 
     }) 
     .ToList().OrderBy(x => x.Text)) 
    { 
     wCollection.List.Add(item); 
    } 
} 

的問題是,這導致了全部的實體從數據庫中,然後被加載預計。 這個問題也很明顯,就是這行「selector.Compile()(x)」。

我的問題是我不知道如何讓這個部分選擇進行到NHibernate作爲投影。 我顯然需要ID選擇器來識別實體,我不想改變方法的調用方式。

有沒有辦法解決這個問題?

回答

1

一種方法做執行部分選擇將改變你的選擇表達爲類型:

System.Linq.Expressions.Expression<Func<T, ObjectWrapper<object>>> 

您需要調用它像:

dropCompany.LoadEntityList(Customer.Company, x => new ObjectWrapper<object>() { Value = x.ID, Text = x.CompanyName, x => x.IsCompany); 

實施:

public void LoadEntityList<T>(T selectedEntity, System.Linq.Expressions.Expression<Func<T, ObjectWrapper<object>>> selector,System.Linq.Expressions.Expression<Func<T,bool>> where = null) where T : FlexyBook.Infrastructure.Entity 
{ 
    var wCollection = new ObjectWrapperCollection<object>(); 
    IQueryable<T> query = FlexyBook.Repository.DomainService<T>.GetDomainService().GetAll(); 
    if (where != null) 
     query = query.Where(where); 
    foreach (var item in query.Select(selector).ToList().OrderBy(x => x.Text)) 
    { 
     wCollection.List.Add(item); 
    } 
}