Shaokan
Shaokan

Reputation: 7684

C# MVC generic repository class with interface

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.

Upvotes: 1

Views: 898

Answers (1)

driis
driis

Reputation: 164291

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.

Upvotes: 5

Related Questions