ECO – Ensure related objects

Sometimes you have a list of objects (say List<PurchaseOrder>) and you want to get all associated objects (say OrderLines) for all the orders in the list. There are 2 ways of doing this in ECO

  1. You call a PersistenceService method which takes the list of orders and a string identifying the association name. I don't like this approach because the name of the association may change during modelling and this wont be picked up as an error until runtime.
  2. You use the overloaded method which takes an IAssociationEnd. I don't like this either because you have to find the IAssociationEnd instance from the meta-model at runtime, and to do this you'd probably use a name anyway.

So, what's the alternative?



public static void EnsureRelatedObjects<T>(this IPersistenceService instance, IEnumerable<T> objects, Expression<Func<T, object>> member) where T : IEcoObject
{
    MemberExpression memberExpression = (MemberExpression)member.Body;
    instance.EnsureRelatedObjects(objects, memberExpression.Member.Name);
}


Now you can write code like this

EcoSpace.Persistence.EnsureRelatedObjects(orders, o => o.Lines);
EcoSpace.Persistence.EnsureRelatedObjects(orders, o => o.Customer);

And it will be checked at compile time too.

Comments

Dmytrii said…
I like this syntax a bit more:
o.EnsureRelatedObjects(x => x.Lines)

We can easily obtain IPersistenceService from the object itself.
Hi Dmitriy

My implementation varies in 2 ways.

Firstly I don't like to have persistence related methods on my business classes, whether they are directly implemented or implemented via an extension.

The second difference is that you are ensuring associations for a single object, my method is fetching all associated objects too but uses a list of objects as the source. If I were to implement a single object approach too I'd still not add it to the business object itself :-)

Popular posts from this blog

Connascence

Convert absolute path to relative path

Printing bitmaps using CPCL