/// <summary> /// Sets the value of an existing <see cref="AttributeValue"/> and saves it to the database or creates a new database record if one doesn't already exist. /// </summary> /// <param name="attributeGuid">The parent <see cref="Rock.Model.Attribute"/> unique identifier.</param> /// <param name="entityId">The ID of the entity - if any - to which this <see cref="AttributeValue"/> belongs.</param> /// <param name="value">The value to be set.</param> /// <param name="previousValue">If a <see cref="AttributeValue"/> already exists in the database, it's current value will be returned, so you can set it back after the current tests complete.</param> /// <param name="newAttributeValueGuid">If a <see cref="AttributeValue"/> doesn't already exist in the database, the <see cref="Guid"/> of the newly-created record will be returned, so you can delete it after the current tests complete.</param> public static void SetAttributeValue(Guid attributeGuid, int?entityId, string value, out string previousValue, out Guid newAttributeValueGuid) { using (var rockContext = new RockContext()) { previousValue = null; newAttributeValueGuid = Guid.Empty; var attributeId = AttributeCache.GetId(attributeGuid); if (!attributeId.HasValue) { return; } var attributeValueService = new AttributeValueService(rockContext); var attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attributeId.Value, entityId); if (attributeValue == null) { attributeValue = new AttributeValue { AttributeId = attributeId.Value, EntityId = entityId, Value = value }; attributeValueService.Add(attributeValue); // Remember this so we can delete this AttributeValue upon cleanup. newAttributeValueGuid = attributeValue.Guid; } else { // Remeber this so we can set it back upon cleanup. previousValue = attributeValue.Value; attributeValue.Value = value; } rockContext.SaveChanges(); } }