'How do I add a custom message to a required property with a min and max size using fluent api?

I am trying to implement fluent API instead of DataAnnotations and i have 2 problems

  1. I don't know how to add a custom message for the required property
  2. I don't know how to specify a minimum size and a maximum size

Example of what I want to do.

I am trying to convert this:

    public class Inventory
    {
        [Key]
        public int inventory_id { get; set; }
        [Required(ErrorMessage = "El campo {0} es obligatorio"), StringLength(20, ErrorMessage = "{0} la longitud debe estar entre {2} y {1}.", MinimumLength = 10)]
        public string name { get; set; }
        public string location { get; set; }
        public bool status { get; set; }
    }

Using fluent API

namespace API.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions options) : base(options)
        {
        }
        public DbSet<Requirement> Requirements { get; set; }
        public DbSet<Inventory> Iventories { get; set; }
        public DbSet<Asset> Assets { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            #region Inventory
            // iventory ID
            modelBuilder.Entity<Inventory>()
                .HasKey(i => i.inventory_id);
            // Name
            modelBuilder.Entity<Inventory>()
            .Property(i => i.name)
            .IsRequired(true, ErrorMessage("is Requerid!"));
            #endregion
        }
    }
}


Solution 1:[1]

The RequiredAttribute is part of the System.ComponentModel.DataAnnotations namespace which is used by a lot of microsoft and others external libraries in different ways based on the destination scope.

E.g.: the ErrorMessage property is used by asp .net MVC to add an error to the ModelState, but in EF Core the same property is simply ignored because it is not applicable to the context (where should ef core put this error message in a database?).

In the end, you still have to put the RequiredAttribute to the model in order to show the error message but at the same time you can use the Required() method in Ef core to set a not null column in the db table.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user1624411