Using RavenDB within an ASP.NET MVC (4) application, what is the correct pattern for loading a set of related entities and passing them to a view?
Taking Stack Overflow as the canonical example, assume the following entities:
class User
{
public int Id { get; set; }
public string UserName { get; set; }
}
class Comment
{
public int Id { get; set; }
public string Body { get; set; }
public string Author{ get; set; }
}
class Question
{
public int Id { get; set; }
// ...
public List<Comment> Comments { get; set; }
public Question()
{
Comments = new List<Comment>();
}
}
What we want to do is display the users information next to the comments under the question, The comments are stored as part of the Question document, so we Include the Comment.Author
Our query might look like this:
var question = RavenSession.Include<Question>(x => x.Author)
.Include<Comment>(x => x.Author)
.Load<Question>(id);
Now we have the question object with all it’s comments, and the Raven client has cached all the user profiles we’ll need, What is the correct / best / most RavenDB approved way of pairing the User objects with the relevant Comments objects?
One thought is that I could transform the User and Comment into a CommentViewModel and send that down to the client, but that seems quite manual.
Another option could be to add another property to the Comment for Author, that is [JsonIgnore]‘d and in the getter, lazy load the user from the Raven session. This feels dirty because the Comment model object would need to hold a reference to the raven session.
You want to do it like this:
This works for 1.2, note.
Then you can just call Load(question.Author) to get the doc from the session cache.