Is it necessary to cache the data for a lazy loaded property with Subsonic 3 simple repository

subsonic

I have added a lazyloaded property called Orders on my Customer class. Do you think it's wise to cache the data in a private field?

private IList<Order> _orders;

[SubSonicIgnore]
public IList<Order> Orders
{
    get
    {
        if (_orders == null)
        {
            var repository = new SimpleRepository("MyConnectionString", SimpleRepositoryOptions.None);
            _orders = repository.Find<Order>(x => x.CustomerId == this.CustomerId);
        }
        return _orders;
    }
}

Or is it better to not cache it like so:

[SubSonicIgnore]
public IList<Order> Orders
{
    get
    {
        var repository = new SimpleRepository("MyConnectionString", SimpleRepositoryOptions.None);
        return repository.Find<Order>(x => x.CustomerId == this.CustomerId);
    }
}

The reason I'm asking is because I think it's a good idea to cache the data for performance sake, but at the same time I'm affraid that caching the data can cause it to become out-of-sync of some other process inserts/deletes records from database.

Best Answer

In your case, your cached Orders will exist for the lifetime of your Customers object. If you needed to clear the cached orders, you could simply requery for your Customer.

If I were you, I'd add an additional property whose name specifies that there is caching, add a custom cacheScope object (like transactionScope, the cache only exists as long as the scope exists), or specify in the documentation which properties will perform caching of child objects and for how long.

I would not remove caching. I'd leave it in there as an additional property. You'll have it if you need it.

Thanks for showing your caching logic. Here's mine. In my case, the life expectancy of my parent object is short, I don't expect >100 records of total parent/child data, and I do expect that all the child data will be used. If my data changes, then I'll need to readdress the caching logic I use in this particular instance:

private static List<HostHeader> _cachedHostHeaders;

public List<HostHeader> CachedHostHeaders
{
    get
    {
        if (_cachedHostHeaders == null)
            _cachedHostHeaders = this.HostHeaders.ToList();

        return _cachedHostHeaders.Where(i => i.SiteID == this.ID).ToList();
    }
}