diff --git a/src/Orchard.Web/Modules/Orchard.Taxonomies/Handlers/TermsPartHandler.cs b/src/Orchard.Web/Modules/Orchard.Taxonomies/Handlers/TermsPartHandler.cs index 1a73399d0..910c0e262 100644 --- a/src/Orchard.Web/Modules/Orchard.Taxonomies/Handlers/TermsPartHandler.cs +++ b/src/Orchard.Web/Modules/Orchard.Taxonomies/Handlers/TermsPartHandler.cs @@ -60,13 +60,22 @@ namespace Orchard.Taxonomies.Handlers { var queryHint = new QueryHints() .ExpandRecords("ContentTypeRecord", "CommonPartRecord", "TermsPartRecord"); + // Get TermRecordIds for each field before the delegate inside the for iterator. + // This avoids the TermsPart.Record lifetime scope to be disposed when executed, since ContentPart.Record is a LazyField. + var groupedRecordIds = part.Record.Terms + .GroupBy(tci => tci.Field) + .ToDictionary(g => g.Key, + g => g.Select(tci => tci.TermRecord.Id).ToArray()); foreach (var field in part.ContentItem.Parts.SelectMany(p => p.Fields).OfType()) { var tempField = field.Name; field.TermsField.Loader(() => { - var fieldTermRecordIds = part.Record.Terms.Where(t => t.Field == tempField).Select(tci => tci.TermRecord.Id); - // Using context content item's ContentManager instead of injected one to avoid lifetime scope exceptions in case of LazyFields. - var terms = part.ContentItem.ContentManager.GetMany(fieldTermRecordIds, VersionOptions.Published, queryHint); + var terms = Enumerable.Empty(); + if (groupedRecordIds.TryGetValue(tempField, out var fieldTermRecordIds)) { + // Using context content item's ContentManager instead of injected one to avoid lifetime scope exceptions in case of LazyFields. + terms = part.ContentItem.ContentManager.GetMany(fieldTermRecordIds, VersionOptions.Published, queryHint); + } + return terms.ToList(); }); }