public static Content Save(Content content) { if (content == null) { throw new ArgumentNullException(nameof(content)); } if (content.VirtualType == VirtualType.None) { throw new ApplicationException("Content virtual type is undefined."); } // Сохранить контент var helper = new VirtualContentHelper(content.ForceVirtualFieldIds?.ToList()); var newContent = VirtualContentRepository.Save(content); if (content.VirtualType == VirtualType.Join) { newContent = helper.SaveJoinContent(content, newContent); } else if (content.VirtualType == VirtualType.Union) { newContent = helper.SaveUnionContent(content, newContent); } else if (content.VirtualType == VirtualType.UserQuery) { newContent = helper.SaveUserQueryContent(content, newContent); } newContent.NewVirtualFieldIds = helper.NewFieldIds; return(newContent); }
/// <summary> /// Валидация на полях Union контента /// </summary> private void CheckForUnion(EntityObject checkedContent, EntityObject parentContent, Content unionSubContent, IReadOnlyCollection <Field> checkedFields, List <RuleViolation> ruleViolation) { // Если у Union всего один источник, то можно не проверять, так как в этом случае при обновлении checkedContent можно обновить и Union if (unionSubContent.UnionSourceContentIDs.Count() > 1) { // проверить есть ли в ветках других контентов-источников поля с такими же именами // если поле единственное - то можно смело обновлять Union var checkedFieldNames = checkedFields.Distinct(Field.NameComparer).Select(f => f.Name); var allUnionBaseFields = VirtualContentRepository.GetFieldsOfContents(unionSubContent.UnionSourceContentIDs).Where(f => f.ContentId != parentContent.Id); var nameMatchedBaseFieldsCount = allUnionBaseFields.Count(f => checkedFieldNames.Contains(f.Name, Field.NameStringComparer)); if (nameMatchedBaseFieldsCount > 0) { var checkedContentName = string.IsNullOrWhiteSpace(checkedContent.Name) ? ContentStrings.CurrentContent : checkedContent.Name; // получить пары полей с одинаковыми именами var violations = (from scf in unionSubContent.Fields join f in checkedFields on scf.Name.ToLowerInvariant() equals f.Name.ToLowerInvariant() select Tuple.Create(scf, f) ).Distinct(new LambdaEqualityComparer <Tuple <Field, Field> >((t1, t2) => t1.Item1.Id == t2.Item1.Id, t => t.Item1.Name.ToLowerInvariant().GetHashCode())) .Select(t => СheckUnionMatchedFields(checkedContentName, unionSubContent.Name, t.Item1, t.Item2)) .Where(v => v != null); // Выполнить проверку на соответствие полей с одинаковым именем ruleViolation.AddRange(violations); } } }
/// <summary> /// Возвращает список контентов на основе которых можно строить виртуальные контетны типа join /// </summary> /// <param name="siteId"></param> /// <returns></returns> public static IEnumerable <ListItem> GetAcceptableContentForVirtualJoin(int siteId) { if (!SiteRepository.Exists(siteId)) { throw new ArgumentException(string.Format(SiteStrings.SiteNotFound, siteId)); } return(VirtualContentRepository.GetAcceptableContentForVirtualJoin(siteId)); }
/// <summary> /// Обновляет виртуальный контент /// </summary> /// <param name="content"></param> /// <returns></returns> public static Content Update(Content content) { if (content == null) { throw new ArgumentNullException(nameof(content)); } var helper = new VirtualContentHelper(content.ForceVirtualFieldIds?.ToList()); using (VirtualFieldRepository.LoadVirtualFieldsRelationsToMemory(content.Id)) { // Если тип контента изменился // то удалить связанную с контентом информацию if (content.StoredVirtualType != content.VirtualType) { helper.RemoveContentData(content); } // Обновить контент var dbContent = VirtualContentRepository.Update(content); // Спициальное обновления для конкретного типа контента if (content.VirtualType == VirtualType.Join) { dbContent = helper.UpdateJoinContent(content, dbContent); } else if (content.VirtualType == VirtualType.Union) { dbContent = helper.UpdateUnionContent(content, dbContent); } else if (content.VirtualType == VirtualType.UserQuery) { dbContent = helper.UpdateUserQueryContent(content, dbContent); } dbContent.NewVirtualFieldIds = helper.NewFieldIds; return(dbContent); } }
/// <summary> /// Проверка полей базовых контентов для UNION на соответствие /// </summary> public IEnumerable <RuleViolation> UnionFieldsMatchCheck(List <int> unionSourceContentIds) { var contents = ContentRepository.GetList(unionSourceContentIds.Distinct()).ToList(); var contentNames = new Dictionary <int, string>(contents.Count); foreach (var c in contents) { contentNames.Add(c.Id, c.Name); } var unionBaseContentFields = VirtualContentRepository.GetFieldsOfContents(unionSourceContentIds); // Группируем по имени поля var _ = unionBaseContentFields //.GroupBy(f => f.Name, new LambdaComparer<string>((s1, s2) => s1.Equals(s2, StringComparison.InvariantCultureIgnoreCase))); .GroupBy(f => f.Name.ToLowerInvariant()); var result = new List <RuleViolation>(); // Проверяет поля на соответствие var __ = new LambdaEqualityComparer <Field>( (f1, f2) => { var violation = СheckUnionMatchedFields(contentNames[f1.ContentId], contentNames[f2.ContentId], f1, f2); if (violation != null) { result.Add(violation); } return(true); }, f => f.Name.ToLowerInvariant().GetHashCode() ); return(result); }