I'm approaching to document database and I'm little bit confused how to map documents relationship, in a situation as follow
public class Person
{
public Person()
{
}
public int Id { get; set; }
public string Name { get;set;}
public string Surname { get; set; }
public DateTime? BirthDate { get; set; }
}
public class Car
{
public Car() { }
public int Id { get; set; }
public string Name { get; set; }
public int PersonId { get; set;}
}
A person has one or more cars for example in this way I can query the db as follow
public Car Get(int id)
{
Car car = null;
using (IDocumentSession session = store.OpenSession())
{
car = session.Include<Car, Person>(x => x.PersonId).Load<Car>(id);
bool isLoaded = session.Advanced.IsLoaded("people/" + car.PersonId); // true!
}
return car;
}
and it's everything ok, the client makes just one request, but if I have a person and I want to show all his cars how can I query the db to do just a request?
I think tha I must modify the model putting a List<int> Cars
in Person
for reference his cars.
Note that I don't want to embed Cars
in the Person
document because Cars
can be referenced from others document.
Thanks.
You can index the Cars collection and load all the cars from the index.
The index would look like this:
The CarView class is identical to the Car class, but can be changed to better fit the indexing needs.
You'll need to execute the index before being able to use it:
Loading the cars for a certain person would look like this:
If you want to load the person and their cars in a single database request, use lazy loading:
Complete test (needs xunit and RavenDB.Tests.Helpers nugets):