public void Dispose() { if (_cachedEntity != null && _mediaStream != null) { // Get the new entity from the Entity Framework object state manager. ObjectStateEntry entry = this.context.ObjectStateManager.GetObjectStateEntry(_cachedEntity); if (entry.State == EntityState.Unchanged) { { var ctx = new DiscCtx(ConfigManager.ConnStr); ctx.Attach(_cachedEntity); _cachedEntity.MediaData.Data = _mediaStream.ToArray(); ctx.SaveChanges(); } } else { // A problem must have occurred when saving the entity to the database, // so we should delete the entity var mediaData = _cachedEntity.MediaData; _cachedEntity.MediaData = null; var ctx = new DiscCtx(ConfigManager.ConnStr); if (mediaData != null) { ctx.Attach(mediaData); ctx.DeleteObject(mediaData); } ctx.Attach(_cachedEntity); ctx.DeleteObject(_cachedEntity); throw new DataServiceException("An error occurred. The media resource could not be saved."); } } }