How to update a content item (draft) from a background task in Orchard?

I have a simple IBackgroundTask implementation that executes a query and then either performs an insert or one or more updates depending on whether or not a particular element exists. However, updates are not saved, and I do not understand why. New items are created as expected.

The content that I am updating has CommonPart , and I tried authentication as a valid user. I also tried dumping the contents of the manager at the end of the Sweep method. What am I missing?

This is my Sweep , slightly edited for brevity:

 public void Sweep() { // Authenticate as the site super user var superUser = _membershipService.GetUser(_orchardServices.WorkContext.CurrentSite.SuperUser); _authenticationService.SetAuthenticatedUserForRequest(superUser); // Create a dummy "Person" content item var item = _contentManager.New("Person"); var person = item.As<PersonPart>(); if (person == null) { return; } person.ExternalId = Random.Next(1, 10).ToString(); person.FirstName = GenerateFirstName(); person.LastName = GenerateLastName(); // Check if the person already exists var matchingPersons = _contentManager .Query<PersonPart, PersonRecord>(VersionOptions.AllVersions) .Where(record => record.ExternalId == person.ExternalId) .List().ToArray(); if (!matchingPersons.Any()) { // Insert new person and quit _contentManager.Create(item, VersionOptions.Draft); return; } // There are at least one matching person, update it foreach (var updatedPerson in matchingPersons) { updatedPerson.FirstName = person.FirstName; updatedPerson.LastName = person.LastName; } _contentManager.Flush(); } 
+4
source share
1 answer

Try adding _contentManager.Publish(updatedPerson) . If you do not want to publish, but simply for saving, you no longer need to do anything, since changes to Orchard are saved automatically if the violated transaction is not interrupted. Calling Flush not needed at all. This happens both during a regular request and in a background job.

+1
source

All Articles