CoderRoller
CoderRoller

Reputation: 1259

Best way to build/map a model from a request and response on Web API 2

In my WebApi 2 application I have this basic structure:

Request / Response Models -> Domain (Business) Models -> EF Data Models

WebApi Controllers -> Services Layer -> Models Layer -> EF Repository Layer

MyModel.cs file

public class MyModel
{
       public string Property1 { get; set; }
       public string Property2 { get; set; }

       public MyModel(){}

       public MyModel(RedirectRequest request,RedirectResponse response)
       {
           Property1 = request.Property1;
           Property2 = request.Property2;
           /*... (more logic here)*/
       }
}

Service.cs file (injected and used in the controllers)

public void SaveMyModel(RedirectRequest request,RedirectResponse response)
        {
            var myModel = new Domain.MyModel(request,response);
            /*...*/ 
            var myDataModel = Mapper.Map<Data.Models.MyModel>(myModel);           
            _repository.AddOrUpdate(myDataModel);
        }

public  async Task<RedirectResponse> RedirectAndSaveRequest(RedirectRequest request)
        {
            var response = await Redirect(request);
            SaveMyModel(redirect,response);

            return response;
        }

I was debating about the correct way to the construction/mapping of my domain/business model using the request and response models for then to be persisted.

MyModel instance needs both a request and response models to be built according to some business/logic rules as I've shown.

I don't feel right leaving these rules out of the domain Model itself to keep it from being anemic or build an extra class or layer (business or mapping layer or class?) just to do this logic based mapping, cause it seems overkill. A friend told me it should be driven by MVC (with anemic/dummy/POCO models acting like DTO's on a DTO like pattern) which I don't agree with completely.

What is the correct way for this approach?. Thanks a lot for the insight everyone.

Upvotes: 2

Views: 3876

Answers (1)

alltej
alltej

Reputation: 7285

The API layer will have a reference to the Service layer which contains the rich domain models. If you distribute the client wrapper/SDK for your API, you can create a separate project that only contains the data contracts (anemic models, DTOs, POCOs). That way you have a common project for your data contracts which can be used by consuming projects/clients. If not your models can live in the same project as your API project.

In your API layer/project, create mappers using Automapper profiles which all it does is map the domain models to your API models/data contracts.

Upvotes: 2

Related Questions