2
現在,這是一個有趣的問題,因爲你不能做到這一點:實體框架4:如何將字符串轉換爲.OrderBy對象(p => p.fieldname)?
var a = myDB.Where(p => p.field == "filter").OrderBy("it." + fieldname);
你可以改變在哪裏接受一個字符串,它允許您更改排序依據接受一個字符串,但是這不是問題。
如何將「productID,productName」這樣的字符串轉換爲OrderBy表達式?如果我的思想正確,可能問題可能是「如何將規範模式轉換爲表達式委託?」
問題是我不知道他們想要什麼表,因此我不知道主鍵。我使用泛型來表示表的類型。
public interface IRepository<E, C> where C : ObjectContext // E is an Entity
{
void Add(E entity);
void Del(E entity);
IList<E> Get(Expression<Func<E, bool>> filterLambda = null, //Where clause
Expression<Func<E, object>> orderbyLambda = null, //OrderBy
int? page = null, //Page to get
int? pageSize = null, //Page Size
Expression<Func<E, object>> selectLambda = null); //Populate Fields
int Count(Expression<Func<E, bool>> filterLambda = null);
bool SaveChanges();
}
我用拉從數據上下文(數據容器?)內容的實際語句是
this.GetEntity().Where(filterLambda)
.OrderBy(orderbyLambda)
.Skip(((int)page - 1) * (int)pageSize)
.Take((int)pageSize)
.Select(selectLambda).ToList();
我需要的OrderBy()
實施.Skip()
和.Take()
。對於那些認爲你可以這樣做的人來說,對於Linq to SQL來說是正確的。但是,Linq to Entities不支持它:
The method 'Skip' is only supported for sorted input in LINQ to Entities.
The method 'OrderBy' must be called before the method 'Skip'.
讓我們再次嘗試評論:這是一個非常有創意和有效的答案。我想知道是否有辦法將「productid」轉換爲x => x.ProductId。我不會提前知道這些領域,但是這並不貶低這個答案肯定可行。我會試一試。謝謝。 – 2010-10-30 18:05:21
@Dr。 Zim:應該可以通過使用反射來獲取屬性的PropertyInfo,並從中動態創建表達式。 – Guffa 2010-10-30 18:32:09
只是在如何將字符串值轉換回實際對象(即我需要排序的字段)上畫空白。 – 2010-10-30 21:11:43