public EntityObject NewEntityFromOrig(MetadataWorkspace mdw) { var newEntity = Activator.CreateInstance(_detachedEntity.GetType()); var newEntityObj = (EntityObject)newEntity; newEntityObj.EntityKey = _entityKey; //use metadata and Reflection to populate entity var etype = newEntity.GetType(); foreach (var p in etype.GetProperties()) { //find the correct property in origvalues object origPropertyValue; if (_origValues.TryGetValue(p.Name, out origPropertyValue)) { p.SetValue(newEntity, origPropertyValue, null); } else { if (p.PropertyType.Name.StartsWith("EntityReference")) { //there is a "'1" in the propertytype.name var lastReference = p.Name.LastIndexOf("Reference"); var entName = p.Name.Remove(lastReference); var entitySetName = mdw.GetEntitySetName(entName); var eref = (EntityReference)(p.GetValue(newEntity, null)); //be sure that a deleted relationship is added before an added relationship foreach (var rel in _relationships) { if (rel.CurrentEndA.EntitySetName == entitySetName) { //this is the entitykey we want, //but we need to set entityreference.entitykey eref.EntityKey = rel.CurrentEndA; } else if (rel.CurrentEndB.EntitySetName == entitySetName) { eref.EntityKey = rel.CurrentEndB; } } //find entitykey } } } //after this, the calling code needs to attach to context, // then apply property changes using the detached entity return((EntityObject)newEntity); }