private static ModelElement CreateModelElementForEFObjectType(EFObject obj, Partition partition)
        {
            ModelElement modelElement = null;
            var t = obj.GetType();
            if (t == typeof(ConceptualEntityModel))
            {
                modelElement = new EntityDesignerViewModel(partition);
            }
            else if (t == typeof(ConceptualEntityType))
            {
                modelElement = new EntityType(partition);
            }
            else if (t == typeof(ConceptualProperty))
            {
                modelElement = new ScalarProperty(partition);
            }
            else if (t == typeof(ComplexConceptualProperty))
            {
                modelElement = new ComplexProperty(partition);
            }
            else if (t == typeof(Association))
            {
                modelElement = new ViewModel.Association(partition);
            }
            else if (t == typeof(EntityTypeBaseType))
            {
                modelElement = new Inheritance(partition);
            }
            else if (t == typeof(NavigationProperty))
            {
                modelElement = new ViewModel.NavigationProperty(partition);
            }

            return modelElement;
        }
        internal override MemoryStream InternalSaveModel(
            SerializationResult serializationResult, EntityDesignerViewModel modelRoot, string fileName, Encoding encoding,
            bool writeOptionalPropertiesWithDefaultValue)
        {
            IEntityDesignDocData docData = null;
            MemoryStream stream = null;

            Debug.Assert(modelRoot.EditingContext != null, "Designer model root has a null EditingContext");
            if (modelRoot.EditingContext != null)
            {
                // find our doc data; don't use the passed in fileName as this will be the new name
                // during a SaveAs operation
                var artifact = EditingContextManager.GetArtifact(modelRoot.EditingContext);
                if (artifact != null)
                {
                    docData = VSHelpers.GetDocData(PackageManager.Package, artifact.Uri.LocalPath) as IEntityDesignDocData;
                }

                Debug.Assert(docData != null, "Couldn't locate our DocData");
                if (docData != null)
                {
                    var text = docData.GetBufferTextForSaving();
                    if (!string.IsNullOrEmpty(text))
                    {
                        stream = FileUtils.StringToStream(text, encoding) as MemoryStream;
                    }
                }
            }

            // if we don't have a stream, then we couldn't serialize for some reason
            if (stream == null)
            {
                serializationResult.Failed = true;
            }

            return stream;
        }
        /// <summary>
        ///     This method reads the .diagram file and makes sure that shapes exist for every item
        ///     in the .diagram file.
        /// </summary>
        internal static void ReloadDiagram(EntityDesignerViewModel viewModel)
        {
            var diagram = viewModel.GetDiagram();
            if (diagram == null)
            {
                // Empty DSL diagram
                return;
            }

            diagram.ResetWatermark(diagram.ActiveDiagramView);

            // get our artifact
            var artifact = EditingContextManager.GetArtifact(viewModel.EditingContext);
            Debug.Assert(artifact != null);
            if (!artifact.IsDesignerSafe)
            {
                return;
            }

            var diagramModel = viewModel.ModelXRef.GetExisting(diagram) as DesignerModel.Diagram;

            if (diagramModel != null)
            {
                // ensure that we still have all of the parts we need to re-translate from the Model
                EntityModelToDslModelTranslatorStrategy.TranslateDiagram(diagram, diagramModel);
            }
            else
            {
                // this path will usually only happen if an UMFDB extension has deleted the diagram node
                // since we don't have a diagram anymore, lay it all out and create a new one
                if (diagram.ModelElement.EntityTypes.Count < EntityDesignerDiagram.IMPLICIT_AUTO_LAYOUT_CEILING)
                {
                    diagram.AutoLayoutDiagram();
                }
                EntityModelToDslModelTranslatorStrategy.CreateDefaultDiagram(viewModel.EditingContext, diagram);
            }

            // remove "Select All" selection
            if (diagram.ActiveDiagramView != null)
            {
                diagram.ActiveDiagramView.Selection.Set(new DiagramItem(diagram));
            }
        }
        /// <summary>
        ///     This method loads the DSL view model with the items in the artifact's C-Model.
        /// </summary>
        internal void ReloadModel(EntityDesignerViewModel viewModel)
        {
            var diagram = viewModel.GetDiagram();
            if (diagram == null)
            {
                // empty DSL diagram
                return;
            }

            // get our artifact
            var artifact = EditingContextManager.GetArtifact(viewModel.EditingContext) as EntityDesignArtifact;
            Debug.Assert(artifact != null);

            var serializationResult = new SerializationResult();

            var serializationContext = new SerializationContext(GetDirectory(viewModel.Store), artifact.Uri.LocalPath, serializationResult);
            var transactionContext = new TransactionContext();
            transactionContext.Add(SerializationContext.TransactionContextKey, serializationContext);

            var workaroundFixSerializationTransactionValue = false;
            if (viewModel.Store.PropertyBag.ContainsKey("WorkaroundFixSerializationTransaction"))
            {
                workaroundFixSerializationTransactionValue = (bool)viewModel.Store.PropertyBag["WorkaroundFixSerializationTransaction"];
            }

            try
            {
                // To fix performance issue during reload, we turn-off layout during "serialization".
                viewModel.Store.PropertyBag["WorkaroundFixSerializationTransaction"] = true;

                using (var t = viewModel.Store.TransactionManager.BeginTransaction("ReloadModel", true, transactionContext))
                {
                    if (artifact.ConceptualModel() == null)
                    {
                        return;
                    }

                    DesignerModel.Diagram diagramModel = null;

                    // If DiagramId is not string empty, try to get the diagram from the artifact. 
                    // There is a situation where we could not find the diagram given an ID (for example: EDMX Model's Diagram that is created by VS before SQL 11; 
                    // In that case, we assign temporary ID to the diagram and a new ID will be generated every time the model is reloaded.)
                    // We could safely choose the first diagram since multiple diagrams feature didn't exist in VS prior to SQL11 release.
                    if (!string.IsNullOrEmpty(diagram.DiagramId))
                    {
                        diagramModel = artifact.DesignerInfo.Diagrams.GetDiagram(diagram.DiagramId);
                    }

                    if (diagramModel == null)
                    {
                        diagramModel = artifact.DesignerInfo.Diagrams.FirstDiagram;
                    }

                    if (diagramModel != null)
                    {
                        // Re-establish the xref between Escher conceptual model and DSL root model.
                        // and between Escher Diagram model and DSL diagram model.

                        Debug.Assert(viewModel.ModelXRef != null, "Why ModelXRef is null?");
                        if (viewModel.ModelXRef != null)
                        {
                            viewModel.ModelXRef.Add(artifact.ConceptualModel(), viewModel, viewModel.EditingContext);
                            viewModel.ModelXRef.Add(diagramModel, diagram, viewModel.EditingContext);
                            ModelTranslatorContextItem.GetEntityModelTranslator(viewModel.EditingContext)
                                .TranslateModelToDslModel(diagramModel, viewModel.Partition);
                        }
                    }

                    if (t.IsActive)
                    {
                        t.Commit();
                    }
                }
            }
            finally
            {
                viewModel.Store.PropertyBag["WorkaroundFixSerializationTransaction"] = workaroundFixSerializationTransactionValue;
            }
        }
        /// <summary>
        ///     This method will remove all child shapes of the EntityDesignerDiagram.
        /// </summary>
        internal static void ClearDiagram(EntityDesignerViewModel viewModel)
        {
            var diagram = viewModel.GetDiagram();
            if (diagram != null)
            {
                using (var t = viewModel.Store.TransactionManager.BeginTransaction("ClearDiagram", true))
                {
                    // make copy of AllElements so that we don't modify the collection while we are iterating over it.
                    // We are only interested to the model elements that belong to the viewModel; so look at the Partition's ElementDirectory
                    // instead of Store's ElementDirectory which is shared across diagram.
                    Debug.Assert(viewModel.Partition != null, "ViewModel's Partition should never be null.");
                    if (viewModel.Partition != null)
                    {
                        var elementDirectory = viewModel.Partition.ElementDirectory;
                        Debug.Assert(
                            elementDirectory != null, "ElementDirectory in partition for view model :" + diagram.Title + " is null.");
                        if (elementDirectory != null)
                        {
                            var allElements = new List<ModelElement>(elementDirectory.AllElements.Count);
                            allElements.AddRange(elementDirectory.AllElements);

                            foreach (var melem in allElements)
                            {
                                // don't delete our diagram, but remove every other presentation element
                                if (melem is PresentationElement
                                    && (melem is EntityDesignerDiagram) == false)
                                {
                                    melem.Delete();
                                }
                            }
                        }
                    }

                    if (t.IsActive)
                    {
                        t.Commit();
                    }
                }
            }
        }
        /// <summary>
        ///     This method removes all of the child elements of the EntityDesignerViewModel.
        /// </summary>
        internal static void ClearModel(EntityDesignerViewModel viewModel)
        {
            // The assumption is that if ModelXRef is null or we cannot get the diagram, DSL Model is empty
            if (viewModel.ModelXRef == null
                || viewModel.GetDiagram() == null)
            {
                return;
            }

            using (var t = viewModel.Store.TransactionManager.BeginTransaction("ClearModel", true))
            {
                // delete inheritance first
                foreach (var melem in viewModel.ModelXRef.ReferencedViewElements)
                {
                    if (melem is Inheritance)
                    {
                        melem.Delete();
                    }
                }

                // delete associations next
                foreach (var melem in viewModel.ModelXRef.ReferencedViewElements)
                {
                    if (melem is Association)
                    {
                        melem.Delete();
                    }
                }

                // delete entities last
                foreach (var melem in viewModel.ModelXRef.ReferencedViewElements)
                {
                    if (melem is EntityType)
                    {
                        melem.Delete();
                    }
                }

                // clear out the XRef
                viewModel.ModelXRef.Clear();

                if (t.IsActive)
                {
                    t.Commit();
                }
            }
        }
        internal override void SaveModelAndDiagram(
            SerializationResult serializationResult, EntityDesignerViewModel modelRoot, string modelFileName, EntityDesignerDiagram diagram,
            string diagramFileName, Encoding encoding, bool writeOptionalPropertiesWithDefaultValue)
        {
            // only save the model
            base.SaveModel(serializationResult, modelRoot, modelFileName, encoding, writeOptionalPropertiesWithDefaultValue);

            if (!serializationResult.Failed)
            {
                // flip our dirty bit (as long as we aren't trying to save the auto-recovery backup file)
                var artifact = EditingContextManager.GetArtifact(modelRoot.EditingContext);
                Debug.Assert(artifact != null, "Failed to get a valid EFArtifact from the context");

                IEntityDesignDocData docData = null;
                var fileName = String.Empty;
                if (artifact != null)
                {
                    fileName = artifact.Uri.LocalPath;
                }

                docData = VSHelpers.GetDocData(PackageManager.Package, fileName) as IEntityDesignDocData;
                Debug.Assert(docData != null, "Couldn't locate our DocData");
                if (artifact != null
                    && docData != null
                    && !string.Equals(docData.BackupFileName, modelFileName, StringComparison.OrdinalIgnoreCase))
                {
                    artifact.IsDirty = false;
                }

                // SaveDiagram file if the file exists
                // TODO: What happened if saving diagram file failed? Should we rollback the model file?
                var diagramDocData =
                    VSHelpers.GetDocData(PackageManager.Package, fileName + EntityDesignArtifact.ExtensionDiagram) as XmlModelDocData;
                if (diagramDocData != null)
                {
                    int saveIsCancelled;
                    diagramDocData.SaveDocData(VSSAVEFLAGS.VSSAVE_SilentSave, out diagramFileName, out saveIsCancelled);
                }
            }
        }
 private EntityDesignerDiagram CreateDslDiagram(EntityDesignerViewModel evm)
 {
     var docData = DocData as MicrosoftDataEntityDesignDocDataBase;
     EntityDesignerDiagram diagram = null;
     Debug.Assert(docData != null, "DocData is not a type of MicrosoftDataEntityDesignDocDataBase");
     if (docData != null)
     {
         diagram = MicrosoftDataEntityDesignSerializationHelper.Instance.CreateDiagramHelper(docData.GetDiagramPartition(), evm);
         // Set diagram name here otherwise DSL will assign one when diagram is loaded in the view which causes a transaction to be committed.
         // When the transaction is committed our custom DSL rules will get fired. At that point Debug.Assert might be fired because the xref might not properly set.
         // It doesn't matter if the name is the same across multiple diagram because we don't use it.
         diagram.Name = Path.GetFileNameWithoutExtension(DocData.FileName);
     }
     return diagram;
 }
        private static void TranslateDiagramObjectHelper(
            EntityDesignerViewModel viewModel, ModelDiagram.BaseDiagramObject modelDiagramEFObject,
            EFObject modelObjectToFindViewModel, bool updateShapeElements, UpdateShapeInfoCallback updateShapeInfoCallback)
        {
            var diagram = viewModel.GetDiagram();
            EFObject diagramEFObject = modelDiagramEFObject;
            Debug.Assert(diagram != null, "Where is the DSL diagram?");
            Debug.Assert(diagramEFObject != null, "Where is the EFObject corresponding to the diagram?");

            if (diagram != null
                && diagramEFObject != null)
            {
                var shapeElement = viewModel.ModelXRef.GetExisting(diagramEFObject) as ViewModelDiagram.ShapeElement;
                if (shapeElement == null)
                {
                    // find the view model associated with the model EFObject
                    var viewModelElement = viewModel.ModelXRef.GetExisting(modelObjectToFindViewModel);
                    Debug.Assert(viewModelElement != null, "Where is the view model for the model object?");

                    if (viewModelElement != null)
                    {
                        // get the shape element fromm the view model
                        shapeElement = diagram.FindShape(viewModelElement);
                        Debug.Assert(shapeElement != null, "Where is the DSL ShapeElement for the view model?");

                        if (shapeElement != null)
                        {
                            // associate the designer model EFObject with the shape element
                            if ((viewModel.ModelXRef.GetExisting(diagramEFObject) == null)
                                && (viewModel.ModelXRef.GetExisting(shapeElement) == null))
                            {
                                viewModel.ModelXRef.Add(diagramEFObject, shapeElement, viewModel.EditingContext);
                            }
                        }
                    }
                }

                // update the shape information for the element
                if (updateShapeElements && shapeElement != null)
                {
                    updateShapeInfoCallback(shapeElement);
                }
            }
        }
        internal override DslModeling.ModelElement TranslateModelToDslModel(EFObject modelElement, DslModeling.Partition partition)
        {
            DesignerModel.Diagram diagram = null;

            if (modelElement != null)
            {
                diagram = modelElement as DesignerModel.Diagram;
                if (diagram == null)
                {
                    throw new ArgumentException("modelElement should be a diagram");
                }
            }

            // get the service so that we can access the root of the entity model
            var service = _editingContext.GetEFArtifactService();
            if (service == null)
            {
                throw new InvalidOperationException(EntityDesignerResources.Error_NoArtifactService);
            }

            EntityDesignerViewModel entityViewModel = null;

            var entityDesignArtifact = service.Artifact as EntityDesignArtifact;
            Debug.Assert(entityDesignArtifact != null, "Artifact is not type of EntityDesignArtifact");

            if (entityDesignArtifact != null)
            {
                // Only translate the Escher Model to Dsl Model if the artifact is designer safe.
                if (entityDesignArtifact.IsDesignerSafe)
                {
                    // now get the root of the model.
                    var model = entityDesignArtifact.ConceptualModel;
                    Debug.Assert(model != null, "Could not get ConceptualModel from the artifact.");

                    if (model != null)
                    {
                        entityViewModel =
                            ModelToDesignerModelXRef.GetNewOrExisting(_editingContext, model, partition) as EntityDesignerViewModel;
                        entityViewModel.Namespace = model.Namespace.Value;

                        // If the passed-in diagram is null, retrieve the first diagram if available.
                        if (diagram == null
                            && entityDesignArtifact.DesignerInfo() != null
                            && entityDesignArtifact.DesignerInfo().Diagrams != null
                            && entityDesignArtifact.DesignerInfo().Diagrams.FirstDiagram != null)
                        {
                            diagram = entityDesignArtifact.DesignerInfo().Diagrams.FirstDiagram;
                        }

                        IList<ModelEntityType> entities;
                        IList<ModelAssociation> associations;

                        if (diagram != null)
                        {
                            RetrieveModelElementsFromDiagram(diagram, out entities, out associations);
                        }
                        else
                        {
                            entities = model.EntityTypes().ToList();
                            associations = model.Associations().ToList();
                        }
                        TranslateEntityModel(entities, associations, entityViewModel);
                    }
                }
                else
                {
                    // return empty view model if the artifact is not designer safe so the Diagram can show safe-mode watermark
                    entityViewModel = new EntityDesignerViewModel(partition);
                    entityViewModel.EditingContext = _editingContext;
                }
            }

            return entityViewModel;
        }
        internal static void TranslateDiagramObject(
            EntityDesignerViewModel viewModel, ModelDiagram.BaseDiagramObject modelDiagramObject,
            bool updateShapeElements, IList<ViewModelDiagram.ShapeElement> shapesToAutoLayout)
        {
            Debug.Assert(modelDiagramObject is EFObject, "Why did you define a DiagramEFObject that is not an EFObject?");

            var modelEntityTypeShape = modelDiagramObject as DesignerModel.EntityTypeShape;

            // the view model could have gotten deleted as a result of OnEFObjectDeleted() so don't attempt to translate the diagram EFObject.
            if (modelEntityTypeShape != null
                && modelEntityTypeShape.IsDisposed != true
                && modelEntityTypeShape.EntityType.Target != null
                && modelEntityTypeShape.EntityType.Target.IsDisposed != true)
            {
                TranslateDiagramObjectHelper(
                    viewModel, modelDiagramObject, modelEntityTypeShape.EntityType.Target, updateShapeElements,
                    shapeElement =>
                        {
                            var viewEntityTypeShape = shapeElement as EntityTypeShape;
                            var rectangle = new ViewModelDiagram.RectangleD(
                                modelEntityTypeShape.PointX.Value
                                , modelEntityTypeShape.PointY.Value, modelEntityTypeShape.Width.Value, 0.0);
                            viewEntityTypeShape.AbsoluteBounds = rectangle;
                            viewEntityTypeShape.IsExpanded = modelEntityTypeShape.IsExpanded.Value;
                            if (!shapesToAutoLayout.Contains(viewEntityTypeShape))
                            {
                                shapesToAutoLayout.Add(viewEntityTypeShape);
                            }

                            // Loop through all the shape's connectors and add the connector to list to be autolayout if the connector is not manually routed.
                            foreach (var linkShape in viewEntityTypeShape.Link)
                            {
                                if (linkShape.ManuallyRouted == false
                                    && shapesToAutoLayout.Contains(linkShape) == false)
                                {
                                    shapesToAutoLayout.Add(linkShape);
                                }
                            }
                        });

                var dslEntityTypeShape = viewModel.ModelXRef.GetExisting(modelEntityTypeShape) as EntityTypeShape;
                // dslEntityTypeShape is null if the entity-type is deleted, in that case skip sync FillColor property.
                if (dslEntityTypeShape != null)
                {
                    dslEntityTypeShape.FillColor = modelEntityTypeShape.FillColor.Value;
                }
            }
            // the view model could have gotten deleted as a result of OnEFObjectDeleted() so don't attempt to translate the diagram EFObject.
            var modelAssociationConnectorShape = modelDiagramObject as DesignerModel.AssociationConnector;
            if (modelAssociationConnectorShape != null
                && modelAssociationConnectorShape.IsDisposed != true
                && modelAssociationConnectorShape.Association.Target != null
                && modelAssociationConnectorShape.Association.Target.IsDisposed != true)
            {
                TranslateDiagramObjectHelper(
                    viewModel, modelDiagramObject, modelAssociationConnectorShape.Association.Target, true,
                    shapeElement => TranslateAssociationConnectors(
                        shapeElement as AssociationConnector, modelAssociationConnectorShape, shapesToAutoLayout));
            }

            // the view model could have gotten deleted as a result of OnEFObjectDeleted() so don't attempt to translate the diagram EFObject.
            var modelInheritanceConnectorShape = modelDiagramObject as DesignerModel.InheritanceConnector;
            if (modelInheritanceConnectorShape != null
                && modelInheritanceConnectorShape.IsDisposed != true
                && modelInheritanceConnectorShape.EntityType.Target != null
                && modelInheritanceConnectorShape.EntityType.Target.IsDisposed != true)
            {
                var cet = modelInheritanceConnectorShape.EntityType.Target as ConceptualEntityType;
                if (cet != null
                    && cet.BaseType != null
                    && cet.BaseType.RefName != null)
                {
                    TranslateDiagramObjectHelper(
                        viewModel, modelDiagramObject, cet.BaseType, true,
                        shapeElement => TranslateInheritanceConnectors(
                            shapeElement as InheritanceConnector, modelInheritanceConnectorShape, shapesToAutoLayout));
                }
            }
        }
        private static EntityDesignerDiagram TranslateDiagramValues(EntityDesignerViewModel viewModel, DesignerModel.Diagram modelDiagram)
        {
            var diagram = viewModel.GetDiagram();

            Debug.Assert(diagram != null, "Why diagram is null?");
            if (diagram != null)
            {
                if (viewModel.ModelXRef.ContainsKey(modelDiagram) == false)
                {
                    viewModel.ModelXRef.Add(modelDiagram, diagram, viewModel.EditingContext);
                }

                using (var t = diagram.Store.TransactionManager.BeginTransaction("Translate diagram values", true))
                {
                    // set zoom level, grid and scalar property options
                    diagram.ZoomLevel = modelDiagram.ZoomLevel.Value;
                    diagram.ShowGrid = modelDiagram.ShowGrid.Value;
                    diagram.SnapToGrid = modelDiagram.SnapToGrid.Value;
                    diagram.DisplayNameAndType = modelDiagram.DisplayType.Value;
                    diagram.Title = modelDiagram.Name.Value;
                    diagram.DiagramId = modelDiagram.Id.Value;
                    t.Commit();
                }
            }
            return diagram;
        }
        /// <summary>
        ///     Translate model Association into view Association (creates a view Association if not yet created)
        /// </summary>
        /// <param name="viewModel"></param>
        /// <param name="association"></param>
        /// <returns></returns>
        private static ViewModelAssociation TranslateAssociation(
            EntityDesignerViewModel viewModel,
            ModelAssociation association)
        {
            var ends = association.AssociationEnds();

            var end1 = ends[0];
            var end2 = ends[1];

            if (end1.Type.Status == BindingStatus.Known
                && end2.Type.Status == BindingStatus.Known)
            {
                var viewEnd1 =
                    ModelToDesignerModelXRef.GetExisting(viewModel.EditingContext, end1.Type.Target, viewModel.Partition) as
                    ViewModelEntityType;
                var viewEnd2 =
                    ModelToDesignerModelXRef.GetExisting(viewModel.EditingContext, end2.Type.Target, viewModel.Partition) as
                    ViewModelEntityType;

                // Only create association if both entityType exist.
                if (viewEnd1 != null
                    && viewEnd2 != null)
                {
                    var viewAssoc =
                        ModelToDesignerModelXRef.GetNewOrExisting(viewModel.EditingContext, association, viewEnd1, viewEnd2) as
                        ViewModelAssociation;
                    viewAssoc.Name = association.LocalName.Value;

                    viewAssoc.SourceMultiplicity = end1.Multiplicity.Value;

                    viewAssoc.TargetMultiplicity = end2.Multiplicity.Value;

                    // There could be a situation where association is created after navigation property (for example: the user add an entity-type and then add related types ).
                    // In that case we need to make sure that view's association and navigation property are linked.
                    Debug.Assert(
                        end1.Type.Target != null, "Association End: " + end1.DisplayName + " does not reference a valid entity-type.");
                    if (end1.Type.Target != null)
                    {
                        var modelSourceNavigationProperty =
                            ModelHelper.FindNavigationPropertyForAssociationEnd(end1.Type.Target as ConceptualEntityType, end1);
                        if (modelSourceNavigationProperty != null)
                        {
                            var viewSourceNavigationProperty =
                                ModelToDesignerModelXRef.GetExisting(
                                    viewModel.EditingContext, modelSourceNavigationProperty, viewModel.Partition) as
                                ViewModelNavigationProperty;
                            if (viewSourceNavigationProperty != null)
                            {
                                viewAssoc.SourceNavigationProperty = viewSourceNavigationProperty;
                                viewSourceNavigationProperty.Association = viewAssoc;
                            }
                        }
                    }

                    Debug.Assert(
                        end2.Type.Target != null, "Association End: " + end2.DisplayName + " does not reference a valid entity-type.");
                    if (end2.Type.Target != null)
                    {
                        var modelTargetNavigatioNProperty =
                            ModelHelper.FindNavigationPropertyForAssociationEnd(end2.Type.Target as ConceptualEntityType, end2);
                        if (modelTargetNavigatioNProperty != null)
                        {
                            var viewTargetNavigationProperty =
                                ModelToDesignerModelXRef.GetExisting(
                                    viewModel.EditingContext, modelTargetNavigatioNProperty, viewModel.Partition) as
                                ViewModelNavigationProperty;
                            if (viewTargetNavigationProperty != null)
                            {
                                viewAssoc.TargetNavigationProperty = viewTargetNavigationProperty;
                                viewTargetNavigationProperty.Association = viewAssoc;
                            }
                        }
                    }

                    return viewAssoc;
                }
            }
            return null;
        }
        /// <summary>
        ///     Translate base type of a model EntityType into view Inheritance (creates an Inheritance if not yet created)
        /// </summary>
        /// <param name="viewModel"></param>
        /// <param name="entityType"></param>
        /// <returns></returns>
        private static Inheritance TranslateBaseType(EntityDesignerViewModel viewModel, ConceptualEntityType entityType)
        {
            if (entityType.BaseType.Status == BindingStatus.Known)
            {
                var baseType =
                    ModelToDesignerModelXRef.GetExisting(viewModel.EditingContext, entityType.BaseType.Target, viewModel.Partition) as
                    ViewModelEntityType;
                var derivedType =
                    ModelToDesignerModelXRef.GetExisting(viewModel.EditingContext, entityType, viewModel.Partition) as ViewModelEntityType;

                // in Multiple diagram scenario, baseType and derivedType might not exist in the diagram.
                if (baseType != null
                    && derivedType != null)
                {
                    return
                        ModelToDesignerModelXRef.GetNewOrExisting(viewModel.EditingContext, entityType.BaseType, baseType, derivedType) as
                        Inheritance;
                }
            }

            return null;
        }
 /// <summary>
 ///     Translate model EntityType into view EntityType (creates a view EntityType if not yet created)
 /// </summary>
 /// <param name="viewModel"></param>
 /// <param name="entityType"></param>
 /// <param name="processChildren"></param>
 /// <returns></returns>
 private static ViewModelEntityType TranslateEntityType(EntityDesignerViewModel viewModel, ConceptualEntityType entityType)
 {
     var viewET =
         ModelToDesignerModelXRef.GetNewOrExisting(viewModel.EditingContext, entityType, viewModel.Partition) as ViewModelEntityType;
     viewET.Name = entityType.LocalName.Value;
     return viewET;
 }
        private void TranslateEntityModel(
            IEnumerable<ModelEntityType> entityTypes,
            IEnumerable<ModelAssociation> associations,
            EntityDesignerViewModel entityViewModel)
        {
            // create each entity type and add its properties
            foreach (var et in entityTypes)
            {
                var cet = et as ConceptualEntityType;
                Debug.Assert(cet != null, "EntityType is not ConceptualEntityType");
                var viewET = TranslateEntityType(entityViewModel, cet);
                entityViewModel.EntityTypes.Add(viewET);
                TranslatePropertiesOfEntityType(et, viewET);
            }

            // create any inheritance relationships
            foreach (var et in entityTypes)
            {
                var cet = et as ConceptualEntityType;
                Debug.Assert(cet != null, "EntityType is not ConceptualEntityType");
                TranslateBaseType(entityViewModel, cet);
            }

            // create the associations
            foreach (var assoc in associations)
            {
                TranslateAssociation(entityViewModel, assoc);
            }

            // add navigation properties to the entities
            foreach (var et in entityTypes)
            {
                var viewET =
                    ModelToDesignerModelXRef.GetNewOrExisting(entityViewModel.EditingContext, et, entityViewModel.Partition) as
                    ViewModelEntityType;
                Debug.Assert(viewET != null, "Why wasn't the entity shape added already?");
                TranslateNavigationPropertiesOfEntityType(et, viewET);
            }
        }