[英]how can i write a generic query with EF and C#
我想在這樣的實體框架中編寫查詢:
T entity = (from e in myContext.typeof(T) )
我試圖使用字符串concat,但是不能從myContext
獲取成員
更多代碼:
public T GetEntity<T>(Guid entityId, string connectionString)
{
using (RContext rpContext = new RContext(connectionString))
{
var entity = (from e in rpContext.Set<T>()
where e.Id == entityId
select e).FirstOrDefault();
return (T) Convert.ChangeType(entity, typeof(T));
}
}
您可以像下面這樣訪問通用Set
方法:
var entities = (from e in myContext.Set<T>());
更新:您將需要向您的方法添加通用類型約束,以確保通用類型T
將匹配已應用於方法DbContext.Set<T>
的約束。
更新2:您無需強制轉換實體; 它已經是typeof(T)
。
public T GetEntity<T>(Guid entityId, string connectionString)
where T : class
{
using (RContext rpContext = new RContext(connectionString))
{
return (from e in rpContext.Set<T>()
where e.Id == entityId
select e).FirstOrDefault();
}
}
更新3:假定您未附加到linq語法,則可以直接將謂詞傳遞給FirstOrDefault
方法。
public T GetEntity<T>(Guid entityId, string connectionString)
where T : class
{
using (RContext rpContext = new RContext(connectionString))
{
return rpContext.Set<T>().FirstOrDefault(e => e.Id == entityId);
}
}
更新4:在方法內部使用Id
屬性時,您還需要將方法約束為具有該屬性的類型-通過約束公共接口或公共基類。 如果它是基類,則可以刪除class
約束。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.