Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

c# - How to set custom validation just where Entry.state == EntityState.Added

How to set custom validation that when Entry.state == EntityState.Added is true the below code would work! Custom Validation Code:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
class UniqueEmailAddress : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        this.email = (string)value;
        using (G9EntityDataBaseClass oEntity = new G9EntityDataBaseClass())
        {
            if (oEntity.User.Where(u => u.email == email).Count() == 0)
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(ErrorMessageString);
            }
        }
    }
}

use :

[CustomValidation.UniqueEmailAddress]
public string email { set; get; }

i need ((NOT)EntityState.Added):

if (Entry.state != EntityState.Added){
     return ValidationResult.Success;
}

From where should i bring Entry.state

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A method that works well for validation is implementing IValidatableObject in your entity class:

public class User: IValidatableObject

In the Validate method you can gain access to the context to which the entity object is attached at that moment by adding it to the ValidationContext. So your validation could look like:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    var context = (G9EntityDataBaseClass)validationContext.Items["Context"];
    if (context.User
               .Where(u => u.email == email && u.UserID != this.UserID)
               .Any())
    {
        return new ValidationResult(ErrorMessageString);
    }
    else
    {
        return ValidationResult.Success;
    }
}

You add the context to the validation context by overriding this method in your DbContext class:

protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry,
                       IDictionary<object, object> items)
{
    items.Add("Context", this);
    return base.ValidateEntity(entityEntry, items);
}

The logic is simple: validation always fails if there is an identical email that belongs to another user (u.UserID != this.UserID). This applies both to inserting new users (ID = 0) and existing users.

By the way, it's debatable whether you should actually use the context here to access the database, but the alternative, overriding DbContext.ValidateEntity doesn't appeal to me either, because this causes long strands of code full of type casts of which only one is necessary each time. And this code is traversed for each entity that's validated. The Validate method id only executed when its applicable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...