Projection to an immutable type

Posts   
 
    
chand
User
Posts: 72
Joined: 05-Aug-2007
# Posted on: 05-Aug-2007 23:41:13   

Is there any way to fetch the projection results in to an immutable type collection?

I have a type Customer with one read-only property "Name" which can only be set via the constructor.

Now I want to use DataAccessAdapter's FetchProjection method to fetch the Customer Names from database in to IList<Customer> collection

It looks like my Customer type must be mutable for the projection to be successful.

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39614
Joined: 17-Aug-2003
# Posted on: 06-Aug-2007 13:03:21   

This is possible. You should derive a class from DataProjectorToCustomClass and use that class as your projector instead. In that derived class, override AddProjectionResultToContainer. That routine receives the field projectors and the values to set.

Take a look at the DataProjectorToCustomClass<T> class in the runtime lib sourcecode, it's pretty straight forward simple_smile

Frans Bouma | Lead developer LLBLGen Pro
chand
User
Posts: 72
Joined: 05-Aug-2007
# Posted on: 06-Aug-2007 22:03:08   

Thanks Frans. I got it.

In case if any one is interested here is the code I have come up with

public class DataProjectorToImmutableClass<T> : DataProjectorToCustomClass<T> where T : class, new() { private ConstructorInfo _typeConstructor;

  public DataProjectorToImmutableClass(List<T> destination) : base(destination)
  {

  }

  public ConstructorInfo TypeConstructor
  {
     get { return _typeConstructor; }
     private set
     {
        if(value == null)
        {
           throw new ArgumentException("Failed to find a constructor on destination type with the matching projection parameters");
        }
        _typeConstructor = value;
     }
  }

  protected override void AddProjectionResultToContainer(System.Collections.IList projectors, object[] rawProjectionResult)
  {
     T newInstance = new T();
     if(TypeConstructor == null)
     {
        Type[] paramterTypes = new Type[projectors.Count];
        int i = 0;
        foreach(IProjector projector in projectors)
        {
           paramterTypes[i] = projector.ValueType;
           i++;
        }
        TypeConstructor = typeof(T).GetConstructor(paramterTypes);
     }

      TypeConstructor.Invoke(newInstance, rawProjectionResult);

     Destination.Add(newInstance);
  }

}