简体   繁体   中英

Entity Framework 5.0 ValidateOnSaveEnabled not working?

public void Delete<TEntity>(TEntity entity) where TEntity : class, IEntity
{
    this.Configuration.ValidateOnSaveEnabled = false;
    if (!this.Set<TEntity>().Local.Any(d => d.Id == entity.Id))
    {
        this.Set<TEntity>().Attach(entity);
    }
    this.Set<TEntity>().Remove(entity);
    SaveChanges();
    this.Configuration.ValidateOnSaveEnabled = true;
}

The code above throw an exception on the SaveChanges().

[DbUpdateException: Null value for non-nullable member. Member: 'Name'.]

How can I remove the validation when removing an Entity?

Not sure if this is the problem but if you are deleting entity using a stub object then try setting the DbEntityEntry.State to deleted instead. I'm unsure if you even need to turn validateOnSaveEnabled off.

public void Delete<TEntity>(TEntity entity) where TEntity : class, IEntity
{
    this.Configuration.ValidateOnSaveEnabled = false;
    TEntity alreadyAttached = this.Set<TEntity>().Local
                                  .FirstOrDefault(d=>d.Id == entity.Id);
    if(alreadyAttached != null) entity = alreadyAttached;
    this.Entry<TEntity>(entity).State = EntityState.Deleted;
    SaveChanges();
    this.Configuration.ValidateOnSaveEnabled = true;
 }

Edit

What is written above is may not be entirely correct. As pointed out by Pawel it is a DbUpdateException not DbEntityValidationException . The reason that the above may work for you is the handling of the case if the entity is attached.

if(!this.Set<TEntity>().Local.Any(d=>d.Id == entity.Id))
{
    this.Set<TEntity>().Attach(entity);
}
this.Set<TEntity>().Remove(entity);

Consider the case here if the entity is already attached. Not the passed instance of entity (you are just comparing ids) but another instance representing the same entity. Now consider if you have modified this other entity somewhere in code before this point, it would be tracked by the context as modified. You then attempt to remove your passed instance of entity -- the one that is not being tracked -- resulting in a no-op. You then call savechanges and and BAM! DbUpdateException as EF attempts to update the entity you thought you deleted.

The exception you are seeing is not related to validation what you have is DbUpdateException and not a validation exception). The exception message says that then Name property of the entity being saved is null while the column in the database is not nullable. (If validation was turned on it you would probably get a validation error - is it why you were trying to disable it at all?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM