I have a domain object called Campaign which contains a few string properties and a collection of TrackingEntry objects. Whenever I retrieve a query from the document session, this property is empty, even though I have at least one tracking entry saved. How can I approach retrieving the campaign object such that the tracking entry collection is retrieved as well? Here’s the relevant code for the Campaign:
public class Campaign : Entity
{
private ICollection<TrackingEntry> trackingEntries;
public string BrandId { get; set; }
public ICollection<TrackingEntry> TrackingEntries
{
get { return trackingEntries ?? (trackingEntries = new Collection<TrackingEntry>()); }
}
}
The method that has the problem takes in a comma delimited string of brand ids, retrieves all campaigns with those brand ids, loops through and performs some custom logic based on the contents of the tracking entry collection, amongst other things. Here’s the relevant parts:
var brandIds = input.Split(',');
var campaigns = session.Query<Campaign>().Where(x => x.BrandId.In(brandIds));
foreach (var campaign in campaigns)
{
DateTime? dateClaimed = null;
var trackingEntry = campaign.TrackingEntries.FirstOrDefault(x => x.ConsumerId == consumer.Id);
if (trackingEntry != null)
{
dateClaimed = trackingEntry.CreatedOn;
}
}
I know that there is one tracking entry but setting a breakpoint shows an empty collection. I thought it might be raven caching and a stale index but the issue is still here 24 hours after writing the record into the database. I’m thinking that I probably need a map-reduce index to deal with that collection but am still very hazy on how they work. Thoughts?
The only problem is in the way you set up your properties. By default, private fields aren’t serialized, and public properties will only deserialize if you have a setter defined. The setter itself can be public or private. If you’re concerned about initializing your list, just do it in the constructor.
Here is the most simple approach:
The same would work for any collection type. (array, list, enumerable, etc)
An alternative approach would be through attributing. But I think the first approach is better because it keeps your entities free of dependencies, and is easier to read.