[英]Entity Framework generic Where for entities that inherit from a specific class
在這里,我有一個通用的Repository類,該類是從教程頁面復制的,但是具體來說,我的問題在於最后兩個函數。 在我的項目中,我有幾個繼承自CRUDProperties類的目錄實體,並且所有實體中都有一個屬性“ Activo”,我現在要做的是,如果該實體繼承自CRUDProperties類,則將所有具有Activo屬性的實體是的,如果它們不從該類繼承,則僅獲取所有實體。 但是編譯器拋出錯誤,表明T已經定義。 我該怎么辦?
public class Repository<T> where T : class
{
private readonly projectEntities context;
private IDbSet<T> entities;
string errorMessage = string.Empty;
public Repository(projectEntities context)
{
this.context = context;
}
public T GetById(object id)
{
return context.Set<T>().Find(id);
}
// This is the function that throws me a compilation error
public virtual IList<T> GetAll<T>() where T : CRUDProperties
{
return context.Set<T>().Where(c => c.Activo).ToList();
}
public virtual IList<T> GetAll()
{
return context.Set<T>().ToList();
}
}
編譯器抱怨類型參數的命名不明確。 該類已經有一個名為T
的類型參數,因此在類的上下文中,該類型參數名稱已被“采用”。
但是您應該能夠簡單地通過將方法的類型參數重命名為T
其他東西來完成您想做的事情,因此更改后的方法看起來像這樣:
public virtual IList<TCrud> GetAll<TCrud>() where TCrud : CRUDProperties
{
return context.Set<TCrud>().Where(c => c.Activo).ToList();
}
注意:我在這里假設CRUDProperties
是一個類...如果它是一個接口,那么您還需要將class
約束復制到方法中(即,將其更改為where TCrud : class, CRUDProperties
)
使用此方法,您可以將自定義where子句傳遞給GetAll方法
public virtual IList<T> GetAll<T>(Expression<Func<T, bool>> predicate)
{
return context.Set<T>().Where(predicate).ToList();
}
在此方法中,我們首先檢查T類型是否具有Activo屬性,如果找到此屬性,則我們創建一個自定義表達式樹並替換為返回所有記錄的默認謂詞,此函數僅返回activo屬性中值為true的記錄。
public virtual IList<T> GetAll<T>()
{
Expression<Func<T, bool>> predicate = t => true;
if(typeof(T).GetProperty("Activo") != null)
{
var epx = Expression.Parameter(typeof(T), "x");
Expression left = Expression.PropertyOrField(epx, "Activo");
Expression right = Expression.Constant(true);
Expression e1 = Expression.Equal(left, right);
predicate = Expression.Lambda<Func<T, bool>>(e1, new ParameterExpression[] { epx });
}
return context.Set<T>().Where(predicate);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.