MongoDb C # Drivers, is it possible to wrap it in a shared session?

I apologize if I use the wrong terminology here. I still really love the ORM world, but I play with MongoDb and really love what I see. One of the things I don't like is this:

var books = bookRepository.GetCollection<BsonDocument>("books"); 

and

 foreach (var book in books.FindAllAs<Book>()) { Console.WriteLine("Author: {0}, Title: {1}", book.Author, book.Title); } 

I found some NoRM wrapper tutorials in the session , but I can't figure out how to do this using CSharp drivers (the ones that Mongodb recommends / has on its github page).

What I really would like to do is something like this for the first example:

 var bookRepository = MongoRepository<Book>(); // probably should use IoC to resolve this 

and

 foreach (var book in books.FindAll()) 

Voila! I'm probably not the first person to want this, using the lines everywhere, seems a little crazy, although I will give that the textbook is just an example. Is there an example of โ€œbest practiceโ€ to set it all up this way?

Edit: Please let me know if this is a crazy conversation and not how to do something in Mongo, again this is my first test project.

+6
source share
1 answer

Here is a snippet of my project:

 public static MongoCollection<T> GetCollection<T>(string collectionName = null) { if (string.IsNullOrWhiteSpace(collectionName)) { Type g = typeof (T); collectionName = g.Name; } return MongoServer.Create(Config.MongoConnectionString).GetDatabase(Config.Database).GetCollection<T>(collectionName); } 

Now I do not need to specify the collection name as a string if I do not want to override it:

 var collection = GetCollection<MyEntity>(); 

or

 var collection = GetCollection<MyEntity>("SomeOtherCOllection"); 

You can use some flexive utility \ library to pluralize collection names if you want.

In addition, you do not need to specify the type in the Find methods if you set the type when creating an instance of the collection class, as above.

For example, this is how I do it:

 MongoCursor<MyEntity> results = collection.FindAll(); 

or

 MongoCursor<MyEntity> results = collection.Find(query); 
+5
source

Source: https://habr.com/ru/post/891403/


All Articles