DataObjectMapper

by Alex on March 12th, 2010
No notes
Syntax: C#
Show lines - Hide lines - Show in textbox - Download
/// <summary>
    /// DataObjectMapper
    /// Abstract representation of the mapping required to build a business object.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class DataObjectMapper<T> : IDataSourceObjectFactory<T> where T : class
    {
        public  IDataSource DataSource { get; set; }
 
        private readonly IDictionary<MemberExpression, IMap<T>> mappingGraph = new Dictionary<MemberExpression, IMap<T>>();
 
        /// <summary>
        /// Records the mapping of the specified field in the mapper.
        /// </summary>
        /// <typeparam name="TFieldType">The type of the field.</typeparam>
        /// <param name="field">The expression representing the way we access the field of interest.</param>
        /// <returns></returns>
        public FieldMapper<T, TFieldType> Map<TFieldType>(Expression<Func<T, TFieldType>> field)
        {
            var map = new FieldMapper<T, TFieldType>(field);
            mappingGraph.Add(Expression.MakeMemberAccess(field, ((MemberExpression)field.Body).Member), map);
            return map;
        }
 
 
        /// <summary>
        /// Creates the instance of the object this map applies to.
        /// </summary>
        /// <returns></returns>
        public T Create(IDataSource dataSource)
        {
            var instance = (T)Activator.CreateInstance(typeof (T));
            ((List<IMap<T>>)mappingGraph.Values).ForEach(m => m.ToBusinessObject(dataSource, instance));
            return instance;
        }
 
        /// <summary>
        /// Creates a datasource from the specified business object.
        /// </summary>
        /// <param name="businessObject">The business object.</param>
        /// <returns></returns>
        public IDataSource Create<TDataSource>(T businessObject) where TDataSource : IDataSource
        {
            var dataSource = (IDataSource)Activator.CreateInstance(typeof (TDataSource));
            ((List<IMap<T>>) mappingGraph.Values).ForEach(m => m.ToDataSource(businessObject, dataSource));
            return dataSource;
        }
    }

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS