我該如何實現類似以下的內容?具有自定義列名的C#MVC通用存儲庫
public interface IGenericRepository
{
int id { get; }
T GetById<T>() where T : class
}
public class GenericRepository : IGenericRepository
{
//Some code here
public T GetById<T>(int tid) where T : class
{
return from tbl in dataContext.GetTable<T> where tbl.id == tid select tbl;
}
}
,我想用這個如下:
GenericRepository gr = new GenericRepository();
Category cat = gr.GetById<Category>(15);
當然,在這種用法,tbl.id
在GenericRepository給我一個錯誤。
SOLUTION
public class IHasId
{
public int id { get; set; }
}
public interface IGenericRepository
{
int id { get; }
T GetById<T>(int id) where T : IHasId;
}
public class GenericRepository : IGenericRepository
{
public int id
{
get { throw new NotImplementedException(); }
}
public T GetById<T>(int id) where T : IHasId
{
return from tbl in dataContext.GetTable<T> where tbl.id == tid select tbl;
}
}
而除了這些,別忘了定義這個地方你的模型:
public partial class Category : IHasId { }
而且用法是:
Repository rep = new Repository();
Category cat = rep.GetById<Category>(15);
該死!我終於明白了這個問題,除了這些代碼之外,我必須爲每個使用的實體創建一個部分類。說,我有類別表,我不得不創建一個IBase繼承的公共部分類別!多謝,夥計!! – Shaokan
IHasId繼承遺憾:) – Shaokan