Generic T GetByID <K> (K ID_)

I am trying to implement a shared repository using an 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 passed is also generic. I really don't want my business logic to tell me what type ... for example,

    _repository.GetByID<int>(123);

I want to hide the definition of tyoe, but I can not understand where and how to do it.

Most posts in Stackoverflow seem to have their ID as int. I do not want this, since your identifiers will not always be ints!

Any ideas on this issue?

+3
source share
4 answers

I did it

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

I then inherit this interface

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

DI/IoC Unit Testing.

+5

ID object IRepository. int, Guid, string.

, .

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

You can define a method as a type technique:

var t = new Thing();

t.GetById<int>(44);

Where

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

Have you tried to overload ?:

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

Source: https://habr.com/ru/post/1781054/


All Articles