Search code examples
c#.netvalidationasp.net-corefluentvalidation

Fluent Validation C# Unique Id in collection


I have an entity that has a nested collection as a property which I will receive from a front-end application.

I just want to make sure that each item in this collection(ICollection ChildClassCollection) has a unique Id within the model I have received.

I am using FluentValidation and would like to add this validation using it too for consistency.

It's something very simple I couldn`t find an elegant way to solve..

An example:

public class ParentClass
{
    public string Name { get; set; }

    public ICollection<ChildClass> ChildClassCollection { get; set; }
}

public class ChildClass
{
    public int Id { get; set; }

    public string Name { get; set; }
}

Solution

  • Here is what I ended up with: PRetty cleand, plus, when it encounters issue, it will exit

               this.RuleFor(or => or.ChildClassCollection)
                   .Must(this.IsDistinct)
                   .WithMessage("There are more than one entity with the same Id");
    
            public bool IsDistinct(List<UpdateRoleDTO> elements)
            {
                var encounteredIds = new HashSet<int>();
    
                foreach (var element in elements)
                {
                    if (!encounteredIds.Contains(element.Id))
                    {
                       encounteredIds.Add(element.Id);
                    }
                    else
                    {
                        return false;
                    }
                }
    
                return true;
           }