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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

and in which interface should I define T GetByID<T>(int tid) ? or even a better question: do I need to define it within an interface? :D
You are likely to want GetById<T> to be in your base repository interface.
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<T> does not work since it requires a reference type.
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.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.