Monday, 20 August 2012

RIA: Get EntitySet DomainContext extension method

The default RIA class generates an EntitySet for each type in your ObjectContext.While doing some generics data operation in a generic control inheritance, it's difficult to know on which EntitySet of the DomainContext an action should be performed. In my case i only have one EntitySet for each Entity type so i created the following DomainContext extension.
    public static class DomainContextExtension
        /// <summary>
        /// DavidB : This provides a generic access to an entitySet of a given type.
        /// </summary>
        /// <typeparam name="T">An entity type</typeparam>
        public static EntitySet<T> GetEntitySet<T>(this DomainContext source) where T : Entity
            Type domainType = source.GetType();
            var properties = domainType.GetProperties();

            foreach (PropertyInfo pi in properties)
                if (!pi.PropertyType.Name.Contains("EntitySet"))

                var tArgs = pi.PropertyType.GetGenericArguments();

                if (tArgs.Count() > 0 && tArgs.FirstOrDefault() == typeof(T))
                    EntitySet<T> entitySet = (EntitySet<T>)pi.GetValue(source, null);

                    return entitySet;

            return null;

No comments:

Post a Comment