Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello!

I created a validation method which i will get a warning while i am trying to create a duplicate entry. For example "Property name must be unique" but I have already had empty values in the database and when i try to save second empty value then a warning appears again "Property name must be unique". So I am not able to create my empty entries because of this validation.

I am asking for a validation method or improve my validation to add an extra properties which scope "if the value is empyt or null, don't apply this method / or except ..." Otherwise empty values can not be duplicated but I want to keep them also.
Thanks.

What I have tried:

protected override bool IsValid(PropertyValidatorContext context)
  {
      using (var dbContext = new DbContext ())
      {

          var dataId = context.Instance.GetType().GetProperty("Id").GetValue(context.Instance);

          var result = dbContext.Set<TEntity>().Where($"{context.PropertyName} == @0 And Id!=@1", context.PropertyValue, dataId).Any();



          return !result;

      }
  }
Posted
Updated 15-Jun-20 8:28am

1 solution

Just add a check for an empty value at the start of your validation method. Eg:
C#
protected override bool IsValid(PropertyValidatorContext context)
{
    if (context.PropertyValue == null) return true;
    
    ...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900