M
M
mindgrow2018-06-23 00:42:31
C++ / C#
mindgrow, 2018-06-23 00:42:31

How to create an abstract repository?

Good afternoon!
There are several types of entities such as User, Role, Record, Person, and more. For each of these entities, I want to make separate repositories with the same set of methods, but different types used.
At first I thought to implement everything simply using a generic interface, but I thought, why not make a generic abstract repository class in which generic methods will be implemented.
But I ran into such a problem - when working with entities, I use ApplicationDbConext of the following format:

class ApplicationDbContext: DbContext
{
public DbSet Users {get;set;}
public DbSet Roles {get;set;}
....
}

how do I generalize the name of the context field so that each entity type uses a different field name

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
LiptonOlolo, 2018-06-23
@LiptonOlolo

[Column("here is the name of your column")]
Define for each field in all classes derived from the base

E
Evgeny, 2018-06-23
Maltsev @loqiue

Hey! For example, yes.

public interface IEntity<TId> where TId : struct
{
    TId Id { get; set; }
}

public class Person: IEntity<int>
{
    public int Id { get; set; }
    //другие поля
}

public abstract class GenericRepository<TEntity, TKey>: where TKey : struct where TEntity :  IEntity<TKey>
{
    internal ApplicationDbConext context;
    public GenericRepository(ApplicationDbConext context)
    {
        this.context = context;
    }

    //сделаем глупый метод, чисто для примера	
    public async Task<TEntity> FirstOrDefaultAsync(TKey id)
    {
        return await сontext.Set<TEntity>().FirstOrDefaultAsync(x => x.Id.Equals(id));
    }
}

public class PersonRepository: GenericRepository<Person, int>
{
    //методы для PersonRepository
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question