3
votes

I have a REST-style web application that uses EF code first. I'm using AutoMapper to map my classes to DTO classes for passing across the wire, and (hopefully) back.

When I map from my POCO classes to DTOs, I'm actually starting with an EF proxy object, since the objects I'm dealing with were the result of executing some sort of query against my DataContext. This seems to work fine, however.

When I get back a DTO class as part of a POST request, I can use AutoMapper to map it onto my POCO class, and this works fine too.

However because AutoMapper is just new()-ing the POCO objects rather than using the Create method on the EntitySet, I now have a POCO class rather than the corresponding EF proxy class. This makes it harder for me to add the data to my database etc.

How can I persuade AutoMapper to use EntitySet.Create? Or is there another way to achieve the same result?

3
As far as I know AutoMapper it is not extendible with factory methods the way some IoC containers are. It would be an addition that makes perfect sense, but maybe you have to contribute it yourself!Gert Arnold
@GertArnold: Perfect! You should add that as an answer, and I'll accept it.Gary McGill

3 Answers

3
votes

Map.CreateMap creates an IMappingExpression object which has a method ConstructUsing that accepts a function that can be used as factory method for new objects. The mapped properties are used to set values. (This can be overriden by ConvertUsing, by the way).

For details, see Automapper - how to map to constructor parameters instead of property setters, AutoMapper using the wrong constructor, or How to use Automapper to construct object without default constructor.

In your case this could be something like:

Mapper.CreateMap<TDto, TPoco>()
    .ConstructUsing((Func<TDto, TPoco>) (c => context.CreateObject<TPoco>()))
1
votes

May be you can do like this,

First create the required object and then use that instance to map the DTO object,

var poco=EntitySet.Create()

Mapper.Map<DTOtype, POCOtype>(dto, poco); 
0
votes

Suppose you are accepting POCO object in your post method instead of DTO like

[HttpPost]
public ActionResult Save(Student std)
{
    //do the stuff
}

suppose that Student is EF proxy class but when its bound to the form values using Modelbinder, it creates the new objects not the ones associated with data context. So first thing is, there is no difference if you accept DTO's in post and then convert them to proxy classes or you accept proxy classes in the first place. Second thing is that if object already exist in database and you have just created it using automapper, you can associate with datacontext using attach method. and if its new object you will need to call the Add method to save it in the database.