I come up against this over and over again: writing code to create instances of entities (i.e. populate rows into the database) where there are child associations (i.e. FK references) that need to be filled in.
Example:
namespace EomApp1.Formss.AB2.Model
{
public class UnitConversionSource : EomApp1.Formss.AB2.Model.IUnitConversionSource
{
IEnumerable<UnitConversion> IUnitConversionSource.UnitConversions(DirectAgentsEntities model)
{
yield return new UnitConversion
{
Coefficient = 1,
FromUnit = model.Units.First(c => c.Name == "USD"),
ToUnit = model.Units.First(c => c.Name == "USD"),
DateSpan = new DateSpan
{
FromDate = DateTime.Now,
ToDate = DateTime.Now.Add(TimeSpan.FromHours(1))
}
};
}
}
}
Desired: the first execution in a given expiration period (say 10 seconds) model.Units.First(c => c.Name == "USD") executes, the entity is fetched from the database, but subsequently (within the expiration period) comes from a memory cache.
Goal: Prevent a loop that inserts a million rows from making the same select query a million times.
I’m interested, specifically, in a non-intrusive solution that doesn’t affect the way I write the code in the example. This is (hopefully) in the spirit of best practices from a separation of concerns architectural standpoint.
(ps: i’m not sure if my use of the term non-intrusive was the standard semantic – let me know if there’s a better way to prase this)
I’m not sure what is the point of your code but it has obvious and correct solution:
If you know that you have to use some values very often it is correct way to fetch them to some dictionary and handle its lifetime yourselves or within some cache API.
In case of more complex scenarios you can use EF Caching Provider but in such solution your query must be still parsed, hash must be computed, etc. so for your scenario preloading all units to dictionary looks like better way.