Hi
I have a problem w.r.t soft delete and unique validation rule. I have something similar to this:
...
[ValidateUnique("StoreID")]
private string _identifierName;
...
That results in this:
SELECT
COUNT(*)
FROM
dbo.ProductTypes
WHERE
(((ProductTypes.IdentifierName = 'Identifier1' AND ProductTypes.Id <> 8502) AND ProductTypes.StoreId = 8501) AND ProductTypes.DeletedOn IS NULL)
I am also interested in checking entities that are deleted, because these can be undeleted. Having a unique key constraint on the DB for StoreId and IdentifierName will cause problems as the softdelete check prevents a uniqueness check on all relevant records.
Realizing this I went on and started on my SmartUniqueValidationRule, but soon learned that lot of the code, FieldModel, TypeModel, etc.. in the Validate method of UniqueValidationRule is internal (I have the source code), so what to do?
Perhaps you can include another parameter in the constructor of the attribute and the rule to include/exclude soft deleted items when doing uniqueness check?
Or provide a class level ValidateUniqueAttribute(params string[] fieldNames) that does something like this:
...
Invariant.ArgumentNotNull(validationContext, "validationContext");
if ((validationContext.UnitOfWork != null) && (!validationContext.TargetValueIsDefault))
{
var query = new Query(validationContext.Entity.GetType())
{
QueryExpression = (Entity.Attribute(TypeModel.IdFieldName) != validationContext.Entity.IdInternal)),
IncludeDeleted = _includeDeleted
};
foreach (var fieldName in _fieldNames)
{
var scopeValue = validationContext.GetAttributeValue(fieldName);
query.QueryExpression &= ((Entity.Attribute(fieldName) == scopeValue));
}
if (validationContext.UnitOfWork.Count(query) > 0)
{
validationContext.AddError(Message.FormatInvariant(validationContext.TargetName));
}
}