Reputation: 552
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 Select
call, but then I can't query on the id of the document so I have to use session.Load
instead, but this fetches the whole document.
Do I need to create an index for this?
Upvotes: 1
Views: 757
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:
Hope this helps!
Upvotes: 1