Как я могу добиться чего-то вроде следующего примера?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);
Конечно, этот код не работает, так как если я определяю T : class
то tbl.id
часть не будет работать. Но, конечно, должен быть способ реализовать это. Ответ
UPDATE
УЧИТЫВАЯ driis', я делаю следующее, но я до сих пор не могу получить эту работу:
public interface IEntity
{
int id { get; }
}
public interface IGenericRepository : IEntity
{
T GetById<T>(int id);
}
public class GenericRepository : IGenericRepository
{
public T GetById<T>(int id) {
return from tbl in dataContext.GetTable<T> where tbl.id == tid select tbl;
}
}
На данный момент tbl.id
работает, но dataContext.GetTable<T>
дает мне ошибка.
см http://stackoverflow.com/questions/735140/c-linq-to-sql-refectoring-this-generic-getbyid-method – hatchet