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
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);
}
}