开发者

MongoDb's C# Drivers, is it possible to wrap it in a generic session?

开发者 https://www.devze.com 2023-03-16 00:25 出处:网络
I\'m apologizing if I\'m using the wrong terminology here. I\'m still very much in the ORM world, but I\'ve been playing around with MongoDb and really love what I see. One of the things I\'m not liki

I'm apologizing if I'm using the wrong terminology here. I'm still very much in the ORM world, but I've been playing around with MongoDb and really love what I see. One of the things I'm not liking 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've found several tutorials on wrapping NoRM in a session but I can't figure out how to do it using the CSharp Drivers (the ones that Mongodb recommends / has on their github page).

What I'd really 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 strings everywhere seems a bit nutty, though I will grant that the tutorial is just an example. Is there a "best practices" example to setting this all up in such a manner?

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


Here is snippet from 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 dont need to specify a collection name as a string unless I want to override it:

var collection = GetCollection<MyEntity>();

or

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

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

Also, you dont need to specify the type in your Find methods if you specified the type when instantiating a collection class, like I have above.

For example, this is how I do it:

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

or

MongoCursor<MyEntity> results = collection.Find(query);
0

精彩评论

暂无评论...
验证码 换一张
取 消