About GetById in a generic Repository

C

csharper

Hi, I am interested in implementing the Repository pattern for my data store. I searched and found the following article.

http://mikehadlow.blogspot.com/2008/03/using-irepository-pattern-with-linq-to.html

In the article, the generic IRepository interface is as follows:

public interface IRepository<T> where T : class
{
T GetById(int id);
IQueryable<T> GetAll();
void InsertOnSubmit(T entity);
void DeleteOnSubmit(T entity);
[Obsolete("Units of Work should be managed externally to the Repository.")]
void SubmitChanges();
}

My question is with regard to the GetById method, which takes an int argument. Since this is a generic interface, I would assume that the GetById method should also take a generic type argument. Suppose in my business domain, Book's ID is of type varchar(13), and Author's ID is of type int, then this IRepository interface which has declared GetById(int id) won't be applicable to Book.

What's the best practice for this issue? Should I declare GetById as shownbelow?

T GetById(object id);

Any thoughts on this? Thanks.
 
A

Arne Vajhøj

Hi, I am interested in implementing the Repository pattern for my data store. I searched and found the following article.

http://mikehadlow.blogspot.com/2008/03/using-irepository-pattern-with-linq-to.html

In the article, the generic IRepository interface is as follows:

public interface IRepository<T> where T : class
{
T GetById(int id);
IQueryable<T> GetAll();
void InsertOnSubmit(T entity);
void DeleteOnSubmit(T entity);
[Obsolete("Units of Work should be managed externally to the Repository.")]
void SubmitChanges();
}

My question is with regard to the GetById method, which takes an int argument. Since this is a generic interface, I would assume that the GetById method should also take a generic type argument. Suppose in my business domain, Book's ID is of type varchar(13), and Author's ID is of type int, then this IRepository interface which has declared GetById(int id) won't be applicable to Book.

What's the best practice for this issue? Should I declare GetById as shown below?

T GetById(object id);

Any thoughts on this?

Either just always use int keys.

Or create an interface as:

public interface IRepository<T,TID> where T : class
{
T GetById(TID id);
....

(possible with some restrictions on TID as well)

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top