Course contentsShow
← C#
Lesson 1373 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Advanced Data Transformation

Use AutoMapper or similar patterns to map data models between API layers and UI models.

In this lesson, you will learn how to decouple your internal API domain models from your Blazor UI models using AutoMapper to ensure your frontend stays flexible and maintainable.

Bridging the Gap Between API and UI

As your Blazor application matures, you will notice a tension: your database entities often contain metadata, sensitive fields, or complex nested structures that shouldn't be exposed directly to your UI components. Conversely, your Blazor components might need data formatted in a specific way (like combining a FirstName and LastName into a DisplayName) that doesn't exist in your API layer.

Instead of manual "mapping" logic scattered throughout your components, we use the Data Transfer Object (DTO) pattern combined with AutoMapper. This allows you to maintain a clean separation of concerns.

Implementing the Transformation

First, define your DTOs in your Blazor project. These are simple classes designed specifically to be consumed by your components:

public class UserViewModel 
{
    public string FullName { get; set; }
    public string Email { get; set; }
}

Next, configure an AutoMapper profile to define the transformation rules between your UserEntity (from your API) and your UserViewModel:

public class MappingProfile : Profile 
{
    public MappingProfile() 
    {
        CreateMap<UserEntity, UserViewModel>()
            .ForMember(dest => dest.FullName, 
                       opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"));
    }
}

By injecting IMapper into your Blazor components, you can transform data seamlessly:

[Inject] IMapper Mapper { get; set; }

protected override async Task OnInitializedAsync() 
{
    var userEntity = await Http.GetFromJsonAsync<UserEntity>("api/user");
    var uiModel = Mapper.Map<UserViewModel>(userEntity);
}

Why This Matters

If your API schema changes (e.g., adding a MiddleName field), you only need to update your MappingProfile. Your Blazor components remain untouched because they continue to consume the UserViewModel. This prevents a cascade of breaking changes across your UI layer and keeps your component code clean, readable, and focused on presentation rather than data manipulation.

Key Takeaway: Decouple your UI from your backend schema by utilizing AutoMapper to transform domain entities into purpose-built ViewModels.