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