Search code examples
sql-serverasp.net-mvcpocodomain-model

ASP.net Web API - Example pre-existing database Fluent NHibernate and Automapper


I am working through the ASP.net Web API 2 book (Git Hub)

I am trying to use Fluent NHibernate and Automapper to connect to a database. The book uses a fresh database while my database is pre-existing and not necessarily controlled by good practices.

Before joining tables etc. I would like to just be able to get a list of people and add a new person via the API. The only catch is that I would like to return less properties of the actual table and create a new person with even less than the model used to display a new person. I am having trouble understanding the flow of the automapper.

An example table might be

<pre>Person Entity
-person_id(int)
-person_name(varchar(100))
-person_location(int)
-person_phone(varchar(10))
-person_address(varchar(30))
</pre>

The model I want to use includes a subset of the items in the actual table. For example, maybe:

<pre>Person Model
-person_id(int)
-person_name(varchar(100)
-person_location(int)</pre>

There is also a newPerson model

<pre>NewPerson Model
-Name
-location</pre>

I have an Entity with all the person properties like

public virtual int person_id {get;set;}

but I have a model with the subset properties like

public long person_id {get; set;}

In the automapping configuration file I have a class NewPersonToPersonEntityAutoMapperTypeConfigurator and I have another class PersonEntityToPersonAutoMapperTypeConfigurator

I'm confused about how automapper is working. Should the AutoMapper file NewPersonToPersonEntityAutoMapperTypeConfigurator use something like

Mapper.CreateMap<NewPerson, PersonEntity>
.ForMember(opt => opt.person_id, x => x.Ignore())
...
.ForMember(opt => opt.person_address(varchar(30)))

While PersonEntityToPersonAutoMapperTypeConfigurator uses something like

Mapper.CreateMap<PersonEntity, PersonModel>

Can anyone show me a good example of a simple scenario like this with automapper and a pre-existing table with extra unused properties or describe what Automapper should be doing or if I am on the right track?


Solution

  • Daniel - I think you're on the right track. Yes, you need an AutoMapper map for each "direction"... i.e. incoming service message to the EF entity, and from the EF entity to the service return message.

    Your code to ignore certain properties is fine. You just need to make sure the entity is populated appropriately for the INSERT into the database. For example, the person_id column - is that required to be set? Or is that an auto-incrementing column??

    To say it another way... you can certainly use AutoMapper (and our approach in the book) against an existing database. It's still just mapping properties from one type to another type.

    Feel free to send some code my way.