Custom validation unique property - generic classes

后端 未结 3 1205
感动是毒
感动是毒 2021-02-15 05:42

I\'m trying to make a custom validation [IsUnique]. That check if is property value is unique and return a proper message.

This is my code, but this only work for a spec

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-15 06:48

    It would have been nice if there were generic attributes, but such are not supported. However, you can try using the Set method of the DbContext which takes the entity type as a parameter. To query the non-generic DbSet you can use the System.Linq.Dynamic library (you can add it from NuGet). It allows to query the DbSet using string predicates. Here is an example:

    var existingEntityQuery = myContext.Set(validationContext.ObjectType)
         .Where("Name= @0", (string)value);
    var enumerator = existingEntityQuery.GetEnumerator();
    
    if (enumerator.MoveNext())
    {
        var entity = enumerator.Current;
    
        if (entity != null)
        {
             return new ValidationResult("The name already exist", propertiesList);
        }
    }
    

提交回复
热议问题