adamwtiko
adamwtiko

Reputation: 2905

Generic T GetByID<K>(K ID_)

I'm trying to implement a generic repository using the entity framework.

My repository is defined as :

    public class GenericRepository<T> : IRepository<T> where T : class

I want to add a generic GetByID where the type of ID being passed in is generic too. I don't really want my business logic to tell me the type is e.g....

    _repository.GetByID<int>(123);

I want to hide the tyoe definition but can't figure out where or how to do this.

Most posts on Stackoverflow seem to just have their ID's as ints. I don't want this as your identifiers aren't always going to be ints!

Any ideas on this issue?

Upvotes: 4

Views: 1780

Answers (4)

Daniel A. White
Daniel A. White

Reputation: 190945

I did this

interface IRepository<TEntity, TKey> {
     TEntity GetById(TKey id);
}

Then I inherit from this interface

class Person {
     int ID;
}
interface IPersonRepository : IRepository<Person, int> { ... }

This makes it very DI/IoC and Unit Testing friendly too.

Upvotes: 5

Rikalous
Rikalous

Reputation: 4564

You can define a method as accepting a type:

var t = new Thing();

t.GetById<int>(44);

where

public class Thing
{
public void GetById<T>(T id)
{
}
}

Upvotes: 1

Aliostad
Aliostad

Reputation: 81660

I have defined ID as object in my IRepository. Sometimes it is int, sometimes Guid and sometimes string.

It is sub-optimal but it works.

interface IRepository<T>
{
    T GetById(object id);
}

Upvotes: 1

Cade Roux
Cade Roux

Reputation: 89661

Have you tried overloading?:

T GetByID(int anint) {
    return GetByID<int>(anint);
}

Upvotes: 0

Related Questions