Generic object to object mapping with parametrized constructor

Posted by Rody van Sambeek on Stack Overflow See other posts from Stack Overflow or by Rody van Sambeek
Published on 2010-05-27T12:49:37Z Indexed on 2010/05/27 12:51 UTC
Read the original article Hit count: 349

Filed under:
|
|
|

I have a data access layer which returns an IDataRecord. I have a WCF service that serves DataContracts (dto's). These DataContracts are initiated by a parametrized constructor containing the IDataRecord as follows:

[DataContract]
public class DataContractItem
{
    [DataMember]
    public int ID;
    [DataMember]
    public string Title;

    public DataContractItem(IDataRecord record)
    {
        this.ID = Convert.ToInt32(record["ID"]);
        this.Title = record["title"].ToString();
    }
}

Unfortanately I can't change the DAL, so I'm obliged to work with the IDataRecord as input. But in generat this works very well. The mappings are pretty simple most of the time, sometimes they are a bit more complex, but no rocket science.

However, now I'd like to be able to use generics to instantiate the different DataContracts to simplify the WCF service methods. I want to be able to do something like:

public T DoSomething<T>(IDataRecord record) {
    ...
return new T(record);
}

So I'd tried to following solutions:

  1. Use a generic typed interface with a constructor. doesn't work: ofcourse we can't define a constructor in an interface

  2. Use a static method to instantiate the DataContract and create a typed interface containing this static method. doesn't work: ofcourse we can't define a static method in an interface

  3. Use a generic typed interface containing the new() constraint doesn't work: new() constraint cannot contain a parameter (the IDataRecord)

  4. Using a factory object to perform the mapping based on the DataContract Type. does work, but: not very clean, because I now have a switch statement with all mappings in one file.

I can't find a real clean solution for this. Can somebody shed a light on this for me? The project is too small for any complex mapping techniques and too large for a "switch-based" factory implementation.

© Stack Overflow or respective owner

Related posts about c#

Related posts about wcf