P
P
Preis Dmitry2022-03-27 12:17:59
ASP.NET
Preis Dmitry, 2022-03-27 12:17:59

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();
    // ...
}


The problem is this: when implementing the abstract findOneAsync method, which I really want to make nullable, a compilation error occurs if you do not specify a magic . Also, the problem disappears if MongoDatabase is inherited not from an abstract class, but from an interface. But to be honest, I don’t want to do this, it looks wrong, but I could be wrong. Why is this happening? where TModel : default

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nik Faraday, 2022-04-23
@NikFaraday

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 question

Ask a Question

731 491 924 answers to any question