Sven Schelfaut
Sven Schelfaut

Reputation: 552

Getting only a part of a specific Ravendb document

Is it possible to load only a part of a Ravendb document. I want to fetch a document by id, but only some fields should be fetched. I know I can use session.Query with a Selectcall, but then I can't query on the id of the document so I have to use session.Loadinstead, but this fetches the whole document. Do I need to create an index for this?

Upvotes: 1

Views: 757

Answers (1)

Jens Pettersson
Jens Pettersson

Reputation: 1177

You can use something called Results Transformers to achieve this.

Say you have an entity "Customer"

public class Customer
{
    public string Id { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }
    public string PhoneNumber { get; set; }
    public string Email { get; set; }
}

and you want to load only the Id and the Name property, you define a Results Transformer:

public class CustomerNameTransformer : AbstractTransformerCreationTask<Customer>
{
    public CustomerNameTransformer()
    {
        TransformResults = results => from customer in results
                                      select new CustomerNameViewModel
                                      {
                                          Id = customer.Id,
                                          Name = customer.Name
                                      };
    }
}

and your "view model":

public class CustomerNameViewModel
{
    public string Id { get; set; }
    public string Name { get; set; }
}

With this, you can access the Customer entity as a "Customer Name ViewModel" in several ways:

//Load and transform by one id
CustomerNameViewModel viewModel = session.Load<CustomerNameTransformer, CustomerNameViewModel>("customers/1");

//Load and transform by several id's
CustomerNameViewModel[] viewModels = session.Load<CustomerNameTransformer, CustomerNameViewModel>(new[]{ "customers/1", "customers/2"});

//Query and transform
List<CustomerNameViewModel> viewModels = session.Query<Customer>()
    .TransformWith<CustomerNameTransformer, CustomerNameViewModel>()
    .ToList();

Results Transformers are executed server side before the data is returned to the client. They are created by the same IndexCreation task that creates the index definitions on the server.

You can read more about Results Transformers in the documentation:

http://ravendb.net/docs/article-page/2.5/csharp/client-api/querying/results-transformation/result-transformers

Hope this helps!

Upvotes: 1

Related Questions