using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
public static async Task Main()
var options = new DbContextOptionsBuilder<ApplicationDBContext>()
.UseInMemoryDatabase(databaseName: "ApplicationDB")
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"});
using (var context = new ApplicationDBContext(options))
List<Mrekc> mrekcs = context.Mrekcs.ToList();
var _validator = new CreateGroupingCommandValidator(context);
FluentValidation.Results.ValidationResult result = await _validator.ValidateAsync(new CreateGroupingCommand
Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
public class CreateGroupingCommandValidator : AbstractValidator<CreateGroupingCommand>
private readonly IApplicationDBContext _context;
public CreateGroupingCommandValidator(IApplicationDBContext context)
RuleFor(v => v.GroupCode)
.WithMessage("Maximum length is 50.")
.WithMessage("Required.")
.MustAsync((root, groupCode, context) =>
BeUniqueCompositeKey(groupCode, root.GroupRec, new CancellationToken())
.WithMessage("Duplicate Composite key: GroupCode & GroupRec");
.WithMessage("Maximum length is 50.")
.WithMessage("Required.");
RuleFor(v => v.oDescription)
.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 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; }