/// <summary> /// Validates a single entity. /// Skips validation (returns true) if entity is marked Deleted. /// </summary> /// <param name="entityInfo">contains the entity to validate</param> /// <param name="entityErrors">An EntityError is added to this list for each error found in the entity</param> /// <returns>true if entity is valid, false if invalid.</returns> public bool ValidateEntity(EntityInfo entityInfo, List <EntityError> entityErrors) { if (entityInfo.EntityState == EntityState.Deleted) { return(true); } // Perform validation on the entity, based on DataAnnotations. var entity = entityInfo.Entity; var validationResults = new List <ValidationResult>(); if (!Validator.TryValidateObject(entity, new ValidationContext(entity, null, null), validationResults, true)) { var keyValues = _contextProvider.GetKeyValues(entityInfo); var entityTypeName = entity.GetType().FullName; foreach (var vr in validationResults) { entityErrors.Add(new EntityError() { EntityTypeName = entityTypeName, ErrorMessage = vr.ErrorMessage, ErrorName = "ValidationError", KeyValues = keyValues, PropertyName = vr.MemberNames.FirstOrDefault() }); } return(false); } return(true); }
public SaveResult ToSaveResult() { WasUsed = true; // try to prevent reuse in subsequent SaveChanges if (EntityErrors != null) { return(new SaveResult() { Errors = EntityErrors.Cast <Object>().ToList() }); } else { var entities = SaveMap.SelectMany(kvp => kvp.Value.Where(ei => (ei.EntityState != EntityState.Detached)) .Select(entityInfo => entityInfo.Entity)).ToList(); var deletes = SaveMap.SelectMany(kvp => kvp.Value.Where(ei => (ei.EntityState == EntityState.Deleted || ei.EntityState == EntityState.Detached)) .Select(entityInfo => new EntityKey(entityInfo.Entity, ContextProvider.GetKeyValues(entityInfo)))).ToList(); return(new SaveResult() { Entities = entities, KeyMappings = KeyMappings, DeletedKeys = deletes }); } }