S # arp Ошибка перечисления подшивки модели архитектуры

StackOverflow https://stackoverflow.com/questions/1435557

  •  07-07-2019
  •  | 
  •  

Вопрос

Я получаю сообщение об ошибке от связывателя модели SharpArchitecture. " Коллекция была изменена; операция перечисления может не выполняться. " (Трассировка стека внизу).

Мои страницы MVC для создания и редактирования моей SettingsModel выдают ошибку. Это начало происходить, когда мы обновились до версии S # arp Architecture 1.0. Мой класс имеет несколько списков в качестве свойств. Один из списков содержит классы с другим списком в качестве свойства. Я не уверен, какой список выдает ошибку. Может ли кто-нибудь дать указания относительно того, как решить эту проблему или что нужно искать в моих моделях, которые могут вызвать это?

Это мой класс SettingsModel:

public class SettingsModel : Entity
 {
  public SettingsModel() 
  {
   AttributeSettingsList = new List<AttributeSettingsModel>();
  }

  public virtual void AddAttributeSettings(AttributeSettingsModel attSettings)
  {
   AttributeSettingsList.Add(attSettings);
   attSettings.Settings = this;
  }


  [NotNullNotEmpty(Message = "Description must be provided")]
  public virtual string Description { get; set; }

  [DomainSignature]
  [Range(0, 100, Message = "ModelAPercentage must be between 0 and 100")]
  public virtual int ModelAPercentage { get; set; }

  [DomainSignature]
  [Range(0, 100, Message = "ModelBPercentage must be between 0 and 100")]
  public virtual int ModelBPercentage { get; set; }

  public virtual IList<AttributeSettingsModel> AttributeSettingsList { get; set; }

  public virtual IList<EntityMappingModel> EntityMappingList { get; set; }

  public SettingsModel(string Description, int ModelAPercentage, int ModelBPercentage)
   : this() 
  {
   this.Description = Description;
   this.ModelAPercentage = ModelAPercentage;
   this.ModelBPercentage = ModelBPercentage;
  }

 }

Это метод SharpArchitecture, выдающий ошибку:

    private void SetEntityCollectionProperty(ModelBindingContext bindingContext,
        PropertyDescriptor propertyDescriptor, object value) {

        if (value as IEnumerable != null &&
            IsSimpleGenericBindableEntityCollection(propertyDescriptor.PropertyType)) {

            object entityCollection = propertyDescriptor.GetValue(bindingContext.Model);
            Type entityCollectionType = entityCollection.GetType();

            foreach (object entity in (value as IEnumerable)) {
                entityCollectionType.InvokeMember("Add",
                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, entityCollection,
                    new object[] { entity });
            }
        }
    }

Вот трассировка стека:

[InvalidOperationException: коллекция была изменена; операция перечисления может не выполняться.]    System.ThrowHelper.ThrowInvalidOperationException (ресурс ExceptionResource) +51    System.Collections.Generic.Enumerator.MoveNextRare () +7661017    System.Collections.Generic.Enumerator.MoveNext () +61    SharpArch.Web.ModelBinder.SharpModelBinder.SetEntityCollectionProperty (ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, значение объекта) +358    SharpArch.Web.ModelBinder.SharpModelBinder.SetProperty (ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, значение объекта) +61    System.Web.Mvc.DefaultModelBinder.BindProperty (ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +265    SharpArch.Web.ModelBinder.SharpModelBinder.BindProperty (ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +225    System.Web.Mvc.DefaultModelBinder.BindProperties (ControllerContext controllerContext, ModelBindingContext bindingContext) +125    System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel (ControllerContext controllerContext, ModelBindingContext bindingContext, объектная модель) +293    System.Web.Mvc.DefaultModelBinder.BindComplexModel (ControllerContext controllerContext, ModelBindingContext bindingContext) +772    System.Web.Mvc.DefaultModelBinder.BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) +345    SharpArch.Web.ModelBinder.SharpModelBinder.BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) +39    System.Web.Mvc.DefaultModelBinder.UpdateCollection (ControllerContext controllerContext, ModelBindingContext bindingContext, Тип elementType) +408    System.Web.Mvc.DefaultModelBinder.BindComplexModel (ControllerContext controllerContext, ModelBindingContext bindingContext) +756    System.Web.Mvc.DefaultModelBinder.BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) +345    SharpArch.Web.ModelBinder.SharpModelBinder.BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) +39    System.Web.Mvc.DefaultModelBinder.BindProperty (ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +231    SharpArch.Web.ModelBinder.SharpModelBinder.BindProperty (ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +225    System.Web.Mvc.DefaultModelBinder.BindProperties (ControllerContext controllerContext, ModelBindingContext bindingContext) +125    System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel (ControllerContext controllerContext, ModelBindingContext bindingContext, объектная модель) +293    System.Web.Mvc.DefaultModelBinder.BindComplexModel (ControllerContext controllerContext, ModelBindingContext bindingContext) +772    System.Web.Mvc.DefaultModelBinder.BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) +345

Это было полезно?

Решение

Кажется, есть ошибка в острой архитектуре метода SetEntityCollectionProperty. Это в последних четырех строках:

        foreach (object entity in (value as IEnumerable)) {
            entityCollectionType.InvokeMember("Add",
                BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, null, entityCollection,
                new object[] { entity });
        }

Похоже, его целью является заполнение класса коллекции моделей (entityCollection) из значений в IEnumerable, переданных в качестве значения. Однако эти два объекта являются одной и той же ссылкой. Это уже заселено. Когда " Добавить " вызывается метод, изменяется entityCollection, который является тем же объектом, который повторяется. Затем выдается исключение.

Прокомментируйте или удалите этот блок кода, и ваш код должен запуститься.

Другие советы

Комментируйте ли этот блок кода другие функции S # arp?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top