Entity Framework GetValidationErrors empty for unique index

.net c# entity-framework entity-framework-6 validation

Question

Before I save the context, I want to make sure there are no validation problems. I refer to context. I first call context after GetValidationErrors(), which returns null. I use SaveChanges() and receive the duplicate record error for my unique index.

using(var context = new DefaultDbContext())
{
    var user = new User()
    {
        OSIdentity = "test"
    };
    var duplicateUser = new User()
    {
        OSIdentity = "test"
    };
    context.Users.Add(user);
    context.Users.Add(duplicateUser);    
    // this is empty
    var errors = context.GetValidationErrors(); 
    if(errors.Count == 0)
    {
        // this throws the exception for duplicate row for unique index "Idx_UserOSIdentity"
        context.SaveChanges();
    }
}

The column in my user entity reads as follows:

[Index("idx_UserOSIdentity", IsUnique = true)]
[Display(Name = "OSIdentity")]
[Required(AllowEmptyStrings = false, ErrorMessage = "...")]
[StringLength(450, ErrorMessage = "...")]
public string OSIdentity { get; set; }

Why does context not verify the unique index? GetValidationErrors() is called, but a context-based exception is then thrown. SaveChanges()?

1
1
3/3/2017 6:12:11 AM

Accepted Answer

According to EF architecture, this behaviour is intended.

There are four distinct data validations in EF;

Data Annotations: mostly for UI error checks such aslength , email format and theIndexAttribute neither is a validation characteristic, nor does it possess theErrorMessage Additionally, it lacks the attribute and theIsValid () technique that checks it against a variety of acceptable values. That is the cause.getValidationErrors not examining uniqueness

IValidatableObject By adding a "validate" method, you can do more elaborate tests that aren't possible with data annotations.

ValidateEntity : ADbContext a technique that enables database access for database validation. I think that Here, you are able to create your own logic to confirm uniqueness before to saving.

DbUpdateException : Taking picturesdatabase-generated errors Since our database has its own data integrity and EF operates on top of it,SaveChanges() or SaveChangesAsync() If there is a like your instance of failure to be distinctive database integrity problem, the commit is reverted and the errors are returned through an exception.

Where you choose to detect and handle database data integrity errors is entirely up to you.

2
3/3/2017 6:40:17 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow