<p>The current system that I am working on makes use of Castle Activerecord to provide ORM (Object Relational Mapping) between the Domain objects and the database. This is all well and good and at most times actually works well!</p>

<p>The problem comes about with Castle Activerecords support for asynchronous execution, well, more specifically the SessionScope that manages the session that objects belong to. Long story short, bad stuff happens!</p>

<p>We are therefore looking for a way to easily convert (think automagically) from the Domain objects (who know that a DB exists and care) to the DTO object (who know nothing about the DB and care not for sessions, mapping attributes or all thing ORM).</p>

<p>Does anyone have suggestions on doing this. For the start I am looking for a basic One to One mapping of object. Domain object <strong>Person</strong> will be mapped to say <strong>PersonDTO</strong>. I do not want to do this manually since it is a waste.</p>

<p>Obviously reflection comes to mind, but I am hoping with some of the better IT knowledge floating around this site that <em>"cooler"</em>  will be suggested.</p>

<p>Oh, I am working in C#, the ORM objects as said before a mapped with Castle ActiveRecord.</p>

<hr>

<h2>Example code:</h2>

<p>By @ajmastrean's request I have <a href="http://www.fryhard.com/downloads/stackoverflow/ActiveRecordAsync.zip" rel="noreferrer">linked</a> to an example that I have (badly) mocked together. The example has a <strong>capture form</strong>, capture form <strong>controller</strong>, <strong>domain</strong> objects, activerecord <strong>repository</strong> and an <strong>async</strong> helper. It is slightly big (3MB) because I included the ActiveRecored dll's needed to get it running. You will need to create a database called <em>ActiveRecordAsync</em> on your local machine or just change the .config file.</p>

<p>Basic details of example:</p>

<p><strong>The Capture Form</strong></p>

<p>The capture form has a reference to the contoller</p>

<pre><code>private CompanyCaptureController MyController { get; set; } 
</code></pre>

<p>On initialise of the form it calls MyController.Load()
    private void InitForm ()
    {
        MyController = new CompanyCaptureController(this);
        MyController.Load();
    }
This will return back to a method called LoadComplete()</p>

<pre><code>public void LoadCompleted (Company loadCompany)
{
    _context.Post(delegate
    {
         CurrentItem = loadCompany;
         bindingSource.DataSource = CurrentItem;
         bindingSource.ResetCurrentItem();
         //TOTO: This line will thow the exception since the session scope used to fetch loadCompany is now gone.
         grdEmployees.DataSource = loadCompany.Employees;
         }, null);
    }
}
</code></pre>

<p>this is where the <em>"bad stuff"</em> occurs, since we are using the child list of Company that is set as Lazy load.</p>

<p><strong>The Controller</strong></p>

<p>The controller has a Load method that was called from the form, it then calls the Asyc helper to asynchronously call the LoadCompany method and then return to the Capture form's LoadComplete method.</p>

<pre><code>public void Load ()
{
    new AsyncListLoad&lt;Company&gt;().BeginLoad(LoadCompany, Form.LoadCompleted);
}
</code></pre>

<p>The LoadCompany() method simply makes use of the Repository to find a know company.</p>

<pre><code>public Company LoadCompany()
{
    return ActiveRecordRepository&lt;Company&gt;.Find(Setup.company.Identifier);
}
</code></pre>

<p>The rest of the example is rather generic, it has two domain classes which inherit from a base class, a setup file to instert some data and the repository to provide the <strong>ActiveRecordMediator</strong> abilities.</p>

[{'answer_id': 169708, 'author': 'ZeroBugBounce', 'author_id': 11314, 'author_profile': 'https://Stackoverflow.com/users/11314', 'pm_score': 3, 'selected': False, 'text': "<p>I solved a problem very similar to this where I copied the data out of a lot of older web service contracts into WCF data contracts.  I created a number of methods that had signatures like this:</p>\n\n<pre><code>public static T ChangeType&lt;S, T&gt;(this S source) where T : class, new()\n</code></pre>\n\n<p>The first time this method (or any of the other overloads) executes for two types, it looks at the properties of each type, and decides which ones exist in both based on name and type.  It takes this 'member intersection' and uses the DynamicMethod class to emil the IL to copy the source type to the target type, then it caches the resulting delegate in a threadsafe static dictionary.</p>\n\n<p>Once the delegate is created, it's obscenely fast and I have provided other overloads to pass in a delegate to copy over properties that don't match the intersection criteria:</p>\n\n<pre><code>public static T ChangeType&lt;S, T&gt;(this S source, Action&lt;S, T&gt; additionalOperations) where T : class, new()\n</code></pre>\n\n<p>... so you could do this for your Person to PersonDTO example:</p>\n\n<pre><code>Person p = new Person( /* set whatever */);\nPersonDTO = p.ChangeType&lt;Person, PersonDTO&gt;();\n</code></pre>\n\n<p>And any properties on both Person and PersonDTO (again, that have the same name and type) would be copied by a runtime emitted method and any subsequent calls would not have to be emitted, but would reuse the same emitted code <em>for those types in that order</em> (i.e. copying PersonDTO to Person would also incur a hit to emit the code).</p>\n\n<p>It's too much code to post, but if you are interested I will make the effort to upload a sample to SkyDrive and post the link here.</p>\n\n<p>Richard</p>\n"}, {'answer_id': 169727, 'author': 'MattMcKnight', 'author_id': 8136, 'author_profile': 'https://Stackoverflow.com/users/8136', 'pm_score': 0, 'selected': False, 'text': '<p>My apologies for not really putting the details in here, but a basic OO approach would be to make the DTO a member of the ActiveRecord class and have the ActiveRecord delegate the accessors and mutators to the DTO. You could use code generation or refactoring tools to build the DTO classes pretty quickly from the AcitveRecord classes. </p>\n'}, {'answer_id': 310554, 'author': 'Paul Kapustin', 'author_id': 38325, 'author_profile': 'https://Stackoverflow.com/users/38325', 'pm_score': 0, 'selected': False, 'text': '<p>Actually I got totally confussed now.\nBecause you are saying: "We are therefore looking for a way to easily convert (think automagically) from the Domain objects (who know that a DB exists and care) to the DTO object (who know nothing about the DB and care not for sessions, mapping attributes or all thing ORM)."</p>\n\n<ol>\n<li><p>Domain objects know and care about DB? Isn\'t that the whole point of domain objects to contain business logic ONLY and be totally unaware of DB and ORM?....You HAVE to have these objects? You just need to FIX them if they contain all that stuff...that\'s why I am a bit confused how DTO\'s come into picture</p></li>\n<li><p>Could you provide more details on what problems you\'re facing with lazy loading?</p></li>\n</ol>\n'}, {'answer_id': 2694387, 'author': 'januszstabik', 'author_id': 113911, 'author_profile': 'https://Stackoverflow.com/users/113911', 'pm_score': 2, 'selected': False, 'text': '<p>You should automapper that I\'ve blogged about here:</p>\n\n<p><a href="http://januszstabik.blogspot.com/2010/04/automatically-map-your-heavyweight-orm.html#links" rel="nofollow noreferrer">http://januszstabik.blogspot.com/2010/04/automatically-map-your-heavyweight-orm.html#links</a></p>\n\n<p>As long as the properties are named the same on both your objects automapper will handle it.</p>\n'}, {'answer_id': 3043748, 'author': 'Omu', 'author_id': 112100, 'author_profile': 'https://Stackoverflow.com/users/112100', 'pm_score': 2, 'selected': False, 'text': '<p>use <a href="http://valueinjecter.codeplex.com/" rel="nofollow noreferrer">ValueInjecter</a>, with it you can map anything to anything e.g.</p>\n\n<ul>\n<li>object &lt;-> object</li>\n<li>object &lt;-> Form/WebForm</li>\n<li>DataReader -> object</li>\n</ul>\n\n<p>and it has cool features like: flattening and unflattening</p>\n\n<p>the download contains lots of samples</p>\n'}]
['https://Stackoverflow.com/questions/41638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231/']