RavenDB - retrieving part of document

我的未来我决定 提交于 2019-11-30 17:28:19

Tomek,

You can't load a partial document, but you can load a projection.

session.Query<User>()
   .Where(x=>x.Name == name)
   .Select( x=> new { x.Name, x.Email });

That will load only the appropriate fields

From what I've seen you can do this (based on the original "User" scenario above):

public class UserSummary
{
    public string Name { get; set; }
    public string Email { get; set; }
}

Then you can do this:

documentSession.Query<User>().AsProjection<UserSummary>();

Looking at the Raven server it spits this out as part of the query:

?query=&pageSize=128&fetch=Name&fetch=Email&fetch=Id

So it looks like it is querying and returning only a subset of the original object, which is good.

This also works:

documentSession.Query<User>().Select( x=> new User { Name = x.Name, Email= x.Email })

But I don't think that is as clean as returning a UserSummary object.

Some follow up questions to those who have posted responses:

The link to RaccoonBlog has this example:

https://github.com/ayende/RaccoonBlog/blob/master/RaccoonBlog.Web/Infrastructure/Indexes/PostComments_CreationDate.cs

Would that method be preferred over the .AsProjection()? What is the difference between the two approaches?

Tomek, you cannot load only a part of the document.

However, I understand the problem in your case. I recommend to use two seperate documents for each user: One that actually contains the users data (name, passwordhash, email, etc.) and one that contains all the users messages. That way, it is still very cheap to load all the messages of a user and also to load a list of user for general purposes.

This is actually quite similar to how one would model a blog-domain, where you have a post and the posts comments. Take a look at RaccoonBlog to see how this works.

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