Answer the question
In order to leave comments, you need to log in
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;}
....
}
Answer the question
In order to leave comments, you need to log in
[Column("here is the name of your column")]
Define for each field in all classes derived from the base
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 questionAsk a Question
731 491 924 answers to any question