namespace Note.Domain.Entities { using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema;
public classNoteEntity { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long Id { get; set; } public DateTime Dt { get; set; } public string Who { get; set; } public long NoteTypeId { get; set; } public virtual NoteTypeEntity NoteTypeEntity { get; set; }
public string Note { get; set; } public string CompanyKey { get; set; } public string ApplicationSubKey { get; set; } public string ApplicationKey { get; set; } } }
And for that I created a (version 1) validation class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
using FluentValidation; using Note.Domain.Entities;
Normally I annotate the entity object, but the fluent validator gives you a mechanism to move that code into it’s own class. So you can remove the validation annotations.
You need to add this validator to the startup method.
1 2 3 4 5 6
using FluentValidation;
// hook in validators before registering services builder.Services.AddScoped<IValidator<NoteEntity>, NoteValidator>(); builder.Services.AddScoped<IValidator<NoteTypeEntity>, NoteTypeValidator>();
Typically speaking, I will generally add the validators to the repository layer. So in my NoteRepository class I would add the following code
using FluentValidation; using FluentValidation.Results; // // clear object level variables // privatereadonly IValidator<NoteTypeEntity> _noteTypeValidator; // // in the constructor, inject your notification class // publicNoteTypeRepository(NoteDataContext dbContext, ILogger<NoteTypeRepository> logger, IValidator<NoteTypeEntity> noteTypeValidator // addthis ) : base(logger) { _dbContext = dbContext; _noteTypeValidator = noteTypeValidator; // and this } // // add a block to the top of your Create and Update methods // publicasync Task<IBaseResult> CreateNoteType(NoteTypeEntity noteType) { try { // Validate the noteType entity ValidationResult validationResult = _noteTypeValidator.Validate(noteType);