Last active
March 28, 2023 04:22
-
-
Save pedrovasconcellos/c4319023f46bb91f9395d66813c63030 to your computer and use it in GitHub Desktop.
MongoDB Service with method Insert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Threading.Tasks; | |
| using MongoDB.Bson; | |
| using MongoDB.Bson.Serialization; | |
| using MongoDB.Bson.Serialization.Serializers; | |
| using MongoDB.Driver; | |
| namespace VS.Services | |
| { | |
| public class MongoDBService | |
| { | |
| private readonly string _connectionString; | |
| public MongoDBService(string connectionString) | |
| { | |
| this._connectionString = connectionString; | |
| } | |
| public async Task Save<T>(T entity) | |
| { | |
| await this.Insert(entity, this._connectionString); | |
| await Task.CompletedTask; | |
| } | |
| private async Task Insert<T>(T entity, string connectionString) | |
| { | |
| var database = this.GetMongoDatabase(connectionString); | |
| var collection = database.GetCollection<T>(typeof(T).Name); | |
| await collection.InsertOneAsync(entity); | |
| await Task.CompletedTask; | |
| } | |
| private IMongoDatabase GetMongoDatabase(string connectionString) | |
| { | |
| var mongoUrl = MongoUrl.Create(connectionString); | |
| var settings = MongoClientSettings.FromUrl(mongoUrl); | |
| var client = new MongoClient(settings); | |
| return client.GetDatabase(mongoUrl.DatabaseName); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment