Answer the question
In order to leave comments, you need to log in
How to parameterize a database repository?
I just recently got acquainted with the .net platform and for the first time I write a web api as such, and even more so on asp.net core c#, so I apologize in advance for the crypto.
I chose MongoDB as the database, and when creating the repository, the idea came up to completely parameterize it, so that access to different collections was carried out by passing the corresponding models to the parameter. We call _reposiroty.findOneAsync<UserModelDAO>()
- the repository works with the users collection, _reposiroty.findOneAsync<LectureModel>()
it will work with the lectures collection.
I have an implemented MongoDatabase class that inherits from the abstract Database class, and whose encapsulated object in the controller is cast to the parent type.
public abstract class Database {
public abstract Task<TModel?> findOneAsync<TModel>(string key, string value);
// some abstract methods
}
public class MongoDatabase : Database {
// public override async Task<TModel?> findOneAsync<TModel>(string key, string value) {
public override async Task<TModel?> findOneAsync<TModel>(string key, string value) where TModel : default {
var collection = getCollection<TModel>();
var filter = Builders<TModel>.Filter.Eq(key, value);
TModel? res = await collection.Find(filter).SingleOrDefaultAsync();
return res;
}
// ...
}
public class AuthController : ControllerBase {
private Database _repository = new MongoDatabase();
// ...
}
where TModel : default
Answer the question
In order to leave comments, you need to log in
My personal advice:
First, try asp.net mvc first, as asp.net web api is suggested for those programmers who have at least 2 years of commercial experience.
Secondly, for beginners, it is recommended to use the Entity Framework (For MS SQL Server and SSMS)
Thirdly, inheritance from an interface (Correctly called interface implementation, inheritance only from classes) will not create problems for you, especially if you do not have a compilation problem in this case (Which one?)
Fourth, you will need the implementation of the interfaces for the so-called "Pipeline", which you should learn on asp.net mvc
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question