Lazy loading in MongoDB with NoRM

别说谁变了你拦得住时间么 提交于 2019-12-02 00:52:04

问题


I have a model similar to this: (simplified)

Question:

public class Question
{
    public string QuestionID { get; set; }

    public string Title { get; set; }
    public string Body { get; set; }

    public List<Answer> Answers { get; set; }
}

Answer:

public class Answer
{
    public string QuestionID { get; set; }
    public string Body { get; set; }
}

I intend to store the data in MongoDB, and would like to use NoRM with this.

My question is: Is lazy loading supported? Or can I set it up to do lazy-loading on the document store..?

So that requesting a Question, also retrieves the Answers..? (both will be "posts" stored in the same collection on MongoDB)


回答1:


OK, the concept of "Lazy Loading" is mostly foreign to a database like MongoDB. Take a look at your schema: Question has a List of Answers.

In an RDBMS the "lazy" part allows you to load "the list" separately from the original. There are actually two queries happening, you're just trying to delay the second query.

In MongoDB there's only one query happening. The Answers are embedded inside of the question, so your request for Questions automatically includes the list of Answers.

Please take a look at the NORM samples for a better example of this: http://normproject.org/samples

The basic point is that the structure you provided is no longer multiple tables. It's just one collection with embedded documents. So the concept of "Lazy Loading" is really unnecessary because you can't "Lazy Load" one query.




回答2:


I appreciate that this is an old thread, but other people may still be finding it (as I did). Lazy loading is both possible in MongoDB and supported by the C# driver.

Check out the following classes: LazyBsonDocument and LazyBsonArray

From the C# Driver tutorial documentation : "The lazy classes are special in that they defer the deserialization of BSON until it is needed. This is useful for when you only need a field or two out of a complex document because it will not incur the cost of deserializing the entire document or array, but just the pieces that are necessary. This deserialization occurs a level at a time."

At the time of writing the tutorial document can be found here: http://docs.mongodb.org/ecosystem/tutorial/use-csharp-driver/

The example given is very similar to the question in that it involved a nested collection, so it looks like the list of answers could indeed be lazy loaded if that was desirable.

Hope this helps someone,

Nick



来源:https://stackoverflow.com/questions/3989791/lazy-loading-in-mongodb-with-norm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!