FluentValidation as a Composite Key

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;

public class Program
{
	public static async Task Main()
	{
		var options = new DbContextOptionsBuilder<ApplicationDBContext>()
            .UseInMemoryDatabase(databaseName: "ApplicationDB")
            .Options;

        // Insert seed data into the database using one instance of the context
        using (var context = new ApplicationDBContext(options))
        {
            context.Mrekcs.Add(new Mrekc {GroupCode = "T", GroupRec = "123"});
            context.Mrekcs.Add(new Mrekc {GroupCode = "T", GroupRec = "321"});
            context.Mrekcs.Add(new Mrekc {GroupCode = "K", GroupRec = "123"});
			context.Mrekcs.Add(new Mrekc {GroupCode = "M", GroupRec = "123"});
            context.SaveChanges();
        }

        // Use a clean instance of the context to run the test
        using (var context = new ApplicationDBContext(options))
        {
            //MovieRepository movieRepository = new MovieRepository(context);
            List<Mrekc> mrekcs = context.Mrekcs.ToList();
			
			var _validator = new CreateGroupingCommandValidator(context);
			FluentValidation.Results.ValidationResult result = await _validator.ValidateAsync(new CreateGroupingCommand
																	 {
																		 GroupCode = "K",
																		 GroupRec = "123"
																	 });		
			
			Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
        }
	}
}

public class CreateGroupingCommandValidator : AbstractValidator<CreateGroupingCommand>
{
	private readonly IApplicationDBContext _context;
	public CreateGroupingCommandValidator(IApplicationDBContext context)
	{
		_context = context;
		RuleFor(v => v.GroupCode)
			.MaximumLength(50)
			.WithMessage("Maximum length is 50.")
			//.MustAsync(BeUniqueName)
			//.WithMessage("Already exists.")
			.NotEmpty()
			.WithMessage("Required.")
			.MustAsync((root, groupCode, context) => 
				 BeUniqueCompositeKey(groupCode, root.GroupRec, new CancellationToken())
			)
			.WithMessage("Duplicate Composite key: GroupCode & GroupRec");
			
		RuleFor(v => v.GroupRec)
			.MaximumLength(50)
			.WithMessage("Maximum length is 50.")
			//.MustAsync(BeUniqueName)
			//.WithMessage("Already exists.")
			.NotEmpty()
			.WithMessage("Required.");
			
		RuleFor(v => v.oDescription)
			.MaximumLength(50)
			.WithMessage("Maximum length is 50.");
	}

	private async Task<bool> BeUniqueName(string codename, CancellationToken cancellationToken)
	{
		return await _context.Mrekcs.AllAsync(x => x.GroupCode != codename, cancellationToken);
	}
	
	private async Task<bool> BeUniqueCompositeKey(string groupCode, string groupRec, CancellationToken cancellationToken)
	{
		return await _context.Mrekcs.AllAsync(x => x.GroupCode != groupCode && x.GroupRec != groupRec, cancellationToken);
	}
}

public interface IApplicationDBContext
{
	public DbSet<Mrekc> Mrekcs { get; set; }
}

public class ApplicationDBContext : DbContext, IApplicationDBContext
{
	public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
    {

    }

    public DbSet<Mrekc> Mrekcs { get; set; }
}

[PrimaryKey(nameof(GroupCode), nameof(GroupRec))]
public class Mrekc
{
	public string GroupCode { get; set; }
	public string GroupRec { get; set; }
	public string oDescription { get; set; }
}

public class CreateGroupingCommand
{
	public string GroupCode { get; set; }
	public string GroupRec { get; set; }
	public string oDescription { get; set; }
}
;