Type conversion during projection

Posts   
 
    
iturner
User
Posts: 32
Joined: 07-Sep-2006
# Posted on: 13-Feb-2007 16:29:55   

Hi,

I've been enjoying my first experience of projecting onto custom classes today. All good fun.

One hurdle i did stumble across was when the source type of a field did not match the destination type in my custom class. The approach i saw suggested in a couple of posts was to use a subclassed value projector. Seemed to make sense, so i knocked up a little generics-based one:

public class MyDataValueProjector<TSource, TDestination> : DataValueProjector where TSource : IConvertible where TDestination : IConvertible
    {
        public MyDataValueProjector(string projectedResultName, int valueIndex) 
            : base(projectedResultName, valueIndex) {}

        protected override object ValuePostProcess(object preliminaryProjectionResult, object[] sourceValues)
        {
            #region Various tests lifted from the ORM source
            if (sourceValues == null)
                throw new ArgumentNullException("sourceValues can't be null", "sourceValues");
            
            if (sourceValues.Length <= 0) return null;
            
            if ((this.ValueIndex < 0) || (this.ValueIndex >= sourceValues.Length)) return null;
            #endregion

            // Get the source value
            object sourceValue = sourceValues[this.ValueIndex];

            // Ensure source is of correct type
            if (sourceValue.GetType() != typeof(TSource))
                throw new ArgumentException(string.Format("sourceValue must be of type {0}", typeof(TSource).FullName));

            // Convert
            return Convert.ChangeType(sourceValue, typeof(TDestination));
        }
    }

Very simple, but it's been useful to me today. Others may or may not find it so. But i feel better about myself for having shared it!

Cheers Ian

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39620
Joined: 17-Aug-2003
# Posted on: 13-Feb-2007 21:41:20   

Thanks for the feedback and the code! simple_smile I'll move your thread to General if you don't mind. It's not really a bug wink

Frans Bouma | Lead developer LLBLGen Pro