/// <summary> /// Initializes entity members with all data stored in the given entity. /// </summary> /// <param name="existing">Instance of IEntity. Must be compatibile with current entity; otherwise an exception is generated.</param> /// <remarks>Copies all class members. Parent entities are not copied by reference, but cloned (deep copy).</remarks> protected virtual void FromExistingEntity(IEntity existing) { if (_Table == null) _Table = existing.Table.Clone(null); // throw new ArgumentException("Given entity doesn't belong to same table as current entity. Expected " + _Table.TableName + ", but " + existing.Table.TableName + " was provided.", "existing"); if (_Table.TableName != existing.Table.TableName) throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Messages.EntityModelBase_EntityNotFromSameTableExpextedXButGotY, _Table.TableName, existing.Table.TableName), "existing"); // Clone meta. 'this.table' will be instantiated when _Table getter is accessed for the first time. this.tableAlias = existing.Table.Alias; this.dbTableClass = existing.Table.GetType(); this.table = null; // Members mapped to fields. object[] entityValues = CloneObjectArray(existing.ToObjectArray()); FromObjectArray(entityValues); // Parents. Temporary disable relation navigation to prevent possible data-access when cloning parents. bool relationNavigationStatusBeforeParentCloning = existing.RelationshipNavigationEnabled; existing.RelationshipNavigationEnabled = false; foreach (DbRelation fk in _Table.ForeignKeys) { IEntity parent = existing.GetParent(fk); // Only set if not null (it's already null) because when setting parent entity property to NULL // then FK field would also nulled, thus undoing the previous step (field cloning) and causing error. if (parent != null) this.SetParent(fk, parent.Clone() as IEntity); } // Restore original status of relationship navigation. existing.RelationshipNavigationEnabled = relationNavigationStatusBeforeParentCloning; // Behavior. Entity state, relation navigation. this.entityState = existing.EntityState; this.relationshipNavigationEnabled = existing.RelationshipNavigationEnabled; }