1

The solution has a data entities project and an ASP.NET Core 3.1 MVC project using EF Core.

In the data entities project, there is a domain class:

public class BoatMaker
{
     [Key]
     public int Id { get; set; }

     [Required]
     public string Name {get; set;}
}

I want to be able to decorate this like this:

  [Required]
  [Unique]
  public string Name {get; set;}

so that the model will be invalid if the name is already in the database, and the validation error message automatically populated to that effect in the data validation in the view.

How can this be achieved? Can it be done?

The project uses the repository model, injected into the controllers. The DbContext is obvs. in the web project.

1
  • your scenario may require a custom validation but with async support. So either you need to design your own validation pipeline (not using ValidationAttribute because it does not support async) or you can also use RemoteAttribute for the purpose of validating a property. I personally think it's not a good design because it depends on your api endpoint, not your service api. It requires you to expose an end point for validating. Here is the link to how you can use it learn.microsoft.com/en-us/aspnet/core/mvc/models/… Commented Feb 18, 2021 at 18:56

1 Answer 1

1

I think can not be done in application side because it should check with database. you can use Unique Index to prevent duplicate data.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<BoatMaker>()
      .HasIndex(x => x.Name)
      .IsUnique();
}

you can handle sql exception for duplicate data and show appropriate message to user.

Sign up to request clarification or add additional context in comments.

2 Comments

Mmm, yes that's what I've done.. was just wondering if there was a way to do it using annotations. Thank you.
@D.Man I know I'm answering a year and a half late, but an Index attribute on the class will achieve the same effect, so it can be done with annotations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.