1

How can I achieve something like the following example?

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;
   }
}

and I would like to use this as follows:

GenericRepository gr = new GenericRepository();
Category cat = gr.GetById<Category>(15);

Of course this code does not work since if I define T : class then the tbl.id part won't work. But of course, there should be a way to realize this.

UPDATE

Considering driis' answer, I am doing the following, but I still can't get this working:

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;
    }
}

At this point tbl.id works, but dataContext.GetTable<T> is giving me a error.

tereško
  • 58,060
  • 25
  • 98
  • 150
Shaokan
  • 7,438
  • 15
  • 56
  • 80

1 Answers1

5

You can constrain T to be a type that contains an ID, you will likely want an interface for it:

public interface IEntity 
{ 
    int Id { get; }
}

Then declare your generic method as:

public IQueryable<T> GetById<T>(int tid) where T : IEntity
{ 
   return from tbl in dataContext.GetTable<T> where tbl.id == tid select tbl;
}

Of course you will need to implement IEntity for all entities. I am guessing you are using Linq2Sql or similar, in which case you can just make a partial class definition that includes the interface implementation.

driis
  • 161,458
  • 45
  • 265
  • 341
  • and in which interface should I define T GetByID(int tid) ? or even a better question: do I need to define it within an interface? :D – Shaokan Jul 18 '11 at 21:53
  • You are likely to want GetById to be in your base repository interface. – driis Jul 18 '11 at 21:54
  • I am sorry but I am really new at this stuff, can you please provide a full example? Because when I try to implement IEntity GetTable does not work since it requires a reference type. – Shaokan Jul 18 '11 at 21:57
  • IEntity should not have a GetTable method. It should be in IGenericRepository and implemented in GenericRepository, following your model. Remember to pay attention to the generic constraint (the `where :` part, it needs to be the same in the interface and implementation. – driis Jul 18 '11 at 22:00
  • please see my update and help me from there, I'm struggling with this issue for more than 3 hours so there's left a lil for me to go crazy. @driis – Shaokan Jul 18 '11 at 22:51