Towards Dev

A publication for sharing projects, ideas, codes, and new theories.

Follow publication

Mastering Data Validation in ASP.NET Core: A Comprehensive Guide

Tomas Svojanovsky
Towards Dev
Published in
3 min readAug 11, 2024

--

I will reuse the project from this article — Efficient Data Mapping in ASP.NET Core with AutoMapper.

We already have the cat model. First let's try create a controller for creating new cats.

CatCreateDto

The validations are easy to set up. We just add annotations to the fields. There are also other annotations like EmailAddress, Range, RegularExpression, etc.

We want both fields to be required, with a minimum length of 2 characters and a maximum of 100 characters.

using System.ComponentModel.DataAnnotations;

namespace automapperExample.Models.Dto;

public class CatCreateDto
{
[Required]
[MaxLength(100)]
[MinLength(2)]
public string Name { get; set; }

[Required]
[MaxLength(100)]
[MinLength(2)]
public string Color { get; set; }
}

Automapper

Because we created a new DTO, we need to configure AutoMapper to map between the domain model and the DTO.

using AutoMapper;
using automapperExample.Models.Domain;
using automapperExample.Models.Dto;

namespace automapperExample.Mappings;

public class AutoMapperProfiles : Profile
{
public AutoMapperProfiles()
{
CreateMap<Cat, CatDto>().ReverseMap();
CreateMap<Cat, CatCreateDto>().ReverseMap(); // new
}
}

ICatRepository

We will add a new method for creating cats to the interface.

using automapperExample.Models.Domain;

namespace automapperExample.Repositories;

public interface ICatRepository
{
Task<List<Cat>> GetAllAsync();

Task<Cat> CreateAsync(Cat cat); // new
}

CatRepository

We will receive the cat model, save it, and then pass the newly created object back.

using automapperExample.Data;
using automapperExample.Models.Domain;
using Microsoft.EntityFrameworkCore;

namespace automapperExample.Repositories;

public class CatRepository(AutoMapperDbContext dbContext) : ICatRepository
{
// code ...

public async Task<Cat> CreateAsync(Cat cat)
{
await dbContext.AddAsync(cat);
await dbContext.SaveChangesAsync()…

--

--

Published in Towards Dev

A publication for sharing projects, ideas, codes, and new theories.

Written by Tomas Svojanovsky

I'm a full-stack developer. Programming isn't just my job but also my hobby. I like developing seamless user experiences and working on server-side complexities

No responses yet

Write a response