Example #1
0
    protected virtual bool Set <T>(ref T field, T value, [CallerMemberName] string?automaticPropertyName = null)
    {
        if (EqualityComparer <T> .Default.Equals(field, value))
        {
            return(false);
        }

        PropertyInfo?pi = GetPropertyInfo(automaticPropertyName !);

        if (pi == null)
        {
            throw new ArgumentException("No PropertyInfo with name {0} found in {1} or any implemented interface".FormatWith(automaticPropertyName, this.GetType().TypeName()));
        }

        if (value is IMListPrivate && !((IMListPrivate)value).IsNew && !object.ReferenceEquals(value, field))
        {
            throw new InvalidOperationException("Only MList<T> with IsNew = true can be assigned to an entity");
        }

        if (field is INotifyCollectionChanged colb)
        {
            if (AttributeManager <NotifyCollectionChangedAttribute> .FieldContainsAttribute(GetType(), pi))
            {
                colb.CollectionChanged -= ChildCollectionChanged;
            }

            if (AttributeManager <NotifyChildPropertyAttribute> .FieldContainsAttribute(GetType(), pi))
            {
                foreach (var item in (IEnumerable <IModifiableEntity>)colb !)
                {
                    ((ModifiableEntity)item).ClearParentEntity(this);
                }
            }
        }

        if (field is ModifiableEntity modb)
        {
            if (AttributeManager <NotifyChildPropertyAttribute> .FieldContainsAttribute(GetType(), pi))
            {
                modb.ClearParentEntity(this);
            }
        }

        SetSelfModified();
        field = value;

        if (field is INotifyCollectionChanged cola)
        {
            if (AttributeManager <NotifyCollectionChangedAttribute> .FieldContainsAttribute(GetType(), pi))
            {
                cola.CollectionChanged += ChildCollectionChanged;
            }

            if (AttributeManager <NotifyChildPropertyAttribute> .FieldContainsAttribute(GetType(), pi))
            {
                foreach (var item in (IEnumerable <IModifiableEntity>)cola !)
                {
                    ((ModifiableEntity)item).SetParentEntity(this);
                }
            }
        }

        if (field is ModifiableEntity moda)
        {
            if (AttributeManager <NotifyChildPropertyAttribute> .FieldContainsAttribute(GetType(), pi))
            {
                moda.SetParentEntity(this);
            }
        }

        NotifyPrivate(pi.Name);
        NotifyPrivate("Error");
        NotifyToString();

        ClearTemporalError(pi.Name);

        return(true);
    }