Loading references

Developer
Nov 28, 2009 at 3:53 PM

I've made a class making it easy to bulk load references.

If you have a list of persons and want to ensure taht all persons addresses are loaded do it like this:

ReferenceLoader.LoadReference<Person>(persons, p=>p.Address)

Here's the code:

public static class ReferenceLoader
    {
        public static void LoadReference<T>(IEnumerable<T> objects, params string[] references)
        {
            List<IPersistableProxy> toHandle = new List<IPersistableProxy>();
            toHandle.AddRange((from o in objects where o is IPersistableProxy select o as IPersistableProxy));

            if (toHandle.Count > 0)
            {
                var oc = toHandle.ElementAt(0).ObjectContext;
                oc.PersistenceEngine.LoadReference((from item in toHandle select item.Entity), references);

                foreach (var item in toHandle)
                {
                    item.SetReferences();
                }
            }
        }

        public static void LoadReference<T>(IEnumerable<T> objects, params Expression<Func<T, object>>[] references)
        {
            List<string> referenceNames = new List<string>();

            foreach (var item in references)
                referenceNames.Add(GetMember(item).Member.Name);

            LoadReference<T>(objects, referenceNames.ToArray());
        }

        private static MemberExpression GetMember<M,T>(Expression<Func<M,T>> expression)
        {
            MemberExpression memberExpression = null;
            if (expression.Body.NodeType == ExpressionType.Convert)
            {
                var body = (UnaryExpression)expression.Body;
                memberExpression = body.Operand as MemberExpression;
            }
            else if (expression.Body.NodeType == ExpressionType.MemberAccess)
            {
                memberExpression = expression.Body as MemberExpression;
            }

            return memberExpression;
        }
    }