internal DeleteAssociationCommand(Association association)
            : base(association)
        {
            CommandValidation.ValidateAssociation(association);

            SaveDeletedInformation();
        }
        internal AssociationClipboardFormat(
            Association association, EntityTypeClipboardFormat clipboardEntity1, EntityTypeClipboardFormat clipboardEntity2)
            : base(association)
        {
            _associationName = association.LocalName.Value;
            _clipboardEntity1 = clipboardEntity1;
            _clipboardEntity2 = clipboardEntity2;

            var associationEnds = association.AssociationEnds();
            Debug.Assert(
                associationEnds.Count == 2,
                String.Format(CultureInfo.CurrentCulture, "Invalid AssocationEnd counts for Assocation {0}", association.DisplayName));

            if (associationEnds.Count == 2)
            {
                _multiplicity1 = associationEnds[0].Multiplicity.Value;
                _multiplicity2 = associationEnds[1].Multiplicity.Value;
                _associationEndRole1 = associationEnds[0].Role.Value;
                _associationEndRole2 = associationEnds[1].Role.Value;
                if (association.ReferentialConstraint != null)
                {
                    _referentialConstraint = new ReferentialConstraintClipboardFormat(association.ReferentialConstraint);
                }
            }
            else
            {
                _multiplicity1 = String.Empty;
                _multiplicity2 = String.Empty;
                _associationEndRole1 = String.Empty;
                _associationEndRole2 = String.Empty;
            }
        }
        /// <summary>
        ///     Creates a command of that can swap a Navigation Property association ends.
        /// </summary>
        /// <param name="property">The navigation property to change</param>
        /// <param name="association">The association to use.</param>
        /// <param name="end1">The first point to swap</param>
        /// <param name="end2">The second point to swap</param>
        internal ChangeNavigationPropertyCommand(
            NavigationProperty property, Association association, AssociationEnd end1, AssociationEnd end2)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }
            if (association == null)
            {
                throw new ArgumentNullException("association");
            }
            if (end1 == null)
            {
                throw new ArgumentNullException("end1");
            }
            if (end2 == null)
            {
                throw new ArgumentNullException("end2");
            }

            _property = property;
            _association = association;
            _end1 = end1;
            _end2 = end2;
        }
 public MappingAssociation(EditingContext context, Association assoc, MappingEFElement parent)
     : base(context, assoc, parent)
 {
     Debug.Assert(assoc != null, "MappingAssociation cannot accept a null Association");
     Debug.Assert(
         assoc.AssociationSet != null,
         "MappingAssociation cannot accept an Association " + assoc.ToPrettyString() + " with a null AssociationSet");
 }
        internal CreateAssociationConnectorCommand(Diagram diagram, Association association)
        {
            CommandValidation.ValidateAssociation(association);
            Debug.Assert(diagram != null, "diagram is null");

            _diagram = diagram;
            _association = association;
        }
        internal CreateAssociationSetCommand(string name, Association association, ModelSpace modelSpace)
        {
            ValidateString(name);
            CommandValidation.ValidateAssociation(association);

            Name = name;
            Association = association;
            CommandModelSpace = modelSpace;
        }
        /// <summary>
        ///     Creates a command of that can change a Navigation Property
        /// </summary>
        /// <param name="association">The association to use.</param>
        /// <param name="property">The navigation property to change</param>
        internal ChangeNavigationPropertyCommand(NavigationProperty property, Association association)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            _property = property;
            _association = association;
        }
        internal CreateAssociationSetMappingCommand(Association association, EntityType storageEntityType)
            : base(PrereqId)
        {
            CommandValidation.ValidateAssociation(association);
            CommandValidation.ValidateStorageEntityType(storageEntityType);

            EntityContainerMapping = association.Artifact.MappingModel().FirstEntityContainerMapping;
            AssociationSet = association.AssociationSet;
            Association = association;
            StorageEntitySet = storageEntityType.EntitySet as StorageEntitySet;
        }
 internal void Add(Association a, AssociationIdentity aID)
 {
     _associationToAssociationIdentity.Add(a, aID);
     foreach (var table in aID.AssociationTables)
     {
         List<AssociationIdentity> l = null;
         if (false == _dependentEndTablesToAssociationIdentities.TryGetValue(table, out l))
         {
             l = new List<AssociationIdentity>();
             _dependentEndTablesToAssociationIdentities.Add(table, l);
         }
         l.Add(aID);
     }
 }
        internal CreateAssociationSetMappingCommand(
            EntityContainerMapping entityContainerMapping, AssociationSet associationSet, Association association,
            StorageEntitySet storageEntitySet)
            : base(PrereqId)
        {
            CommandValidation.ValidateEntityContainerMapping(entityContainerMapping);
            CommandValidation.ValidateAssociationSet(associationSet);
            CommandValidation.ValidateAssociation(association);
            CommandValidation.ValidateStorageEntitySet(storageEntitySet);

            EntityContainerMapping = entityContainerMapping;
            AssociationSet = associationSet;
            Association = association;
            StorageEntitySet = storageEntitySet;
        }
        internal CreateNavigationPropertyCommand(
            string name, ConceptualEntityType entity, Association association, AssociationEnd end1, AssociationEnd end2)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            Name = name;
            Entity = entity;
            Association = association;
            FromEnd = end1;
            ToEnd = end2;
        }
        /// <summary>
        ///     Creates a command of that can change a Navigation Property
        /// </summary>
        /// <param name="property">The navigation property to change</param>
        /// <param name="association">The association to use.</param>
        /// <param name="multiplicity">Changes the end's multiplicity, this may end up adding or removing conditions on any AssociationSetMappings</param>
        internal ChangeNavigationPropertyCommand(NavigationProperty property, Association association, string multiplicity)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }
            if (association == null)
            {
                throw new ArgumentNullException("association");
            }
            if (string.IsNullOrEmpty(multiplicity))
            {
                throw new ArgumentNullException("multiplicity");
            }

            _property = property;
            _association = association;
            _multiplicity = multiplicity;
        }
 internal InferReferentialConstraints(CommandProcessorContext context, Association association)
 {
     _context = context;
     _association = association;
 }
 internal CreateAssociationSetCommand(string name, Association association)
     : this(name, association, ModelSpace.Conceptual)
 {
 }
 internal void SetCreatedAssociation(Association createdAssociation)
 {
     CreatedAssociation = createdAssociation;
 }
 private ExplorerAssociation AddAssociation(Association assoc)
 {
     ExplorerAssociation explorerAssociation = null;
     if (assoc.EntityModel.IsCSDL)
     {
         explorerAssociation =
             ModelToExplorerModelXRef.GetNew(_context, assoc, this, typeof(ExplorerConceptualAssociation)) as
             ExplorerConceptualAssociation;
     }
     else
     {
         explorerAssociation =
             ModelToExplorerModelXRef.GetNew(_context, assoc, this, typeof(ExplorerStorageAssociation)) as ExplorerStorageAssociation;
     }
     _associations.Insert(explorerAssociation);
     return explorerAssociation;
 }
 internal CreateForeignKeyProperties(CommandProcessorContext context, Association association)
 {
     _context = context;
     _association = association;
 }
        internal static bool CanEditMappingsForAssociation(
            Association association, MappingDetailsWindowContainer windowContainer, ref TreeGridDesignerWatermarkInfo watermarkInfo,
            bool allowMappingEditWithFKs)
        {
            if (association == null)
            {
                throw new ArgumentNullException("association");
            }

            // make sure that we have an EntitySet (or can find one)
            if (association.AssociationSet == null)
            {
                var errorMessage = String.Format(
                    CultureInfo.CurrentCulture, Resources.MappingDetails_ErrMslGeneral,
                    Resources.MappingDetails_ErrMslCantFindAssociationSet);
                watermarkInfo = new TreeGridDesignerWatermarkInfo(errorMessage);
                return false;
            }

            var asms = association.AssociationSet.GetAntiDependenciesOfType<AssociationSetMapping>();

            var rc = association.ReferentialConstraint;
            if (rc != null)
            {
                // allowMappingEditWithFKs is an override flag that suppresses the following watermarks.
                if (allowMappingEditWithFKs == false)
                {
                    if (EdmFeatureManager.GetForeignKeysInModelFeatureState(association.Artifact.SchemaVersion)
                            .IsEnabled())
                    {
                        // set up watermarks association mapping window watermarks when FKs are supported
                        if (rc.IsPrimaryKeyToPrimaryKey())
                        {
                            if (asms.Count > 0)
                            {
                                watermarkInfo = CreateWatermarkInfoPKToPKRC_WithASM(windowContainer);
                            }
                            else
                            {
                                watermarkInfo = CreateWatermarkInfoPKToPKRC_NoASM(windowContainer);
                            }
                            return false;
                        }
                        else
                        {
                            if (asms.Count > 0)
                            {
                                watermarkInfo = CreateWatermarkInfoPKToFKRC_WithASM(windowContainer);
                            }
                            else
                            {
                                watermarkInfo = CreateWatermarkInfoPKToFKRC_NoASM();
                            }
                            return false;
                        }
                    }
                    else
                    {
                        // targeting netfx 3.5.  FKs are not supported
                        if (rc.IsPrimaryKeyToPrimaryKey() == false)
                        {
                            if (asms.Count > 0)
                            {
                                watermarkInfo = CreateWatermarkInfoPKToFKRC_WithASM(windowContainer);
                            }
                            else
                            {
                                watermarkInfo = CreateWatermarkInfoPKToFKRC_NoASM();
                            }
                            return false;
                        }
                    }
                }
            }

            // make sure that there is just one AssociationSetMapping for our set
            if (asms.Count > 1)
            {
                var errorMessage = String.Format(
                    CultureInfo.CurrentCulture, Resources.MappingDetails_ErrMslGeneral,
                    Resources.MappingDetails_ErrMslTooManyAssociationSetMappings);
                watermarkInfo = new TreeGridDesignerWatermarkInfo(errorMessage);
                return false;
            }
            else
            {
                foreach (var asm in asms)
                {
                    // if AssociationSetMapping contains QueryView
                    if (asm.HasQueryViewElement)
                    {
                        var errorMessage = String.Format(
                            CultureInfo.CurrentCulture, Resources.MappingDetails_ErrMslGeneral,
                            Resources.MappingDetails_ErrMslAssociationSetMappingHasQueryView);
                        watermarkInfo = new TreeGridDesignerWatermarkInfo(errorMessage);
                        return false;
                    }

                    // make sure that we fully resolve
                    var errorMsg = string.Empty;
                    if (EnsureResolvedStatus(asm, ref errorMsg) == false)
                    {
                        var errorMessage = String.Format(CultureInfo.CurrentCulture, Resources.MappingDetails_ErrMslGeneral, errorMsg);
                        watermarkInfo = new TreeGridDesignerWatermarkInfo(errorMessage);
                        return false;
                    }

                    // ensure that we don't have any C-side conditions
                    foreach (var cond in asm.Conditions())
                    {
                        if (cond.Name.RefName != null)
                        {
                            var errorMessage = String.Format(
                                CultureInfo.CurrentCulture, Resources.MappingDetails_ErrMslGeneral,
                                Resources.MappingDetails_ErrMslUnsupportedCondition);
                            watermarkInfo = new TreeGridDesignerWatermarkInfo(errorMessage);
                            return false;
                        }
                    }
                }
            }

            foreach (var associationEnd in association.AssociationEnds())
            {
                string duplicatePropertyName;
                var entityType = associationEnd.Type.Target;
                if (!CheckDuplicateEntityProperty(entityType, out duplicatePropertyName))
                {
                    var errorMessage = String.Format(
                        CultureInfo.CurrentCulture, Resources.MappingDetails_ErrDuplicatePropertyNameForAssociationEndEntity,
                        entityType.LocalName.Value, duplicatePropertyName);
                    errorMessage = String.Format(CultureInfo.CurrentCulture, Resources.MappingDetails_ErrMslGeneral, errorMessage);
                    watermarkInfo = new TreeGridDesignerWatermarkInfo(errorMessage);
                    return false;
                }
            }

            return true;
        }
 internal static void ValidateAssociation(Association association)
 {
     ValidateEFElement(association);
 }
        /// <summary>
        ///     A helper method that creates the AssociationSetMapping and also tries to "Intelli-Match" some mappings, that is, if there are
        ///     columns and properties that match by name, we create mappings for the user.
        /// </summary>
        /// <param name="cpc"></param>
        /// <param name="association"></param>
        /// <param name="storageEntityType"></param>
        /// <returns></returns>
        internal static AssociationSetMapping CreateAssociationSetMappingAndIntellimatch(
            CommandProcessorContext cpc, Association association, StorageEntityType storageEntityType)
        {
            var associationSet = association.AssociationSet;
            Debug.Assert(associationSet != null, "An association found that doesn't have an association set");

            var cmd = new CreateAssociationSetMappingCommand(association, storageEntityType);
            CommandProcessor.InvokeSingleCommand(cpc, cmd);

            foreach (var setEnd in associationSet.AssociationSetEnds())
            {
                var builder = new AssociationSetEndMappingBuilderForCommand(setEnd, storageEntityType);
                builder.Build(cpc);
            }

            return cmd.AssociationSetMapping;
        }
        /// <summary>
        ///     This method will add an InferReferentialContraints IntegrityCheck for the passed in
        ///     association.
        /// </summary>
        /// <param name="cpc"></param>
        /// <param name="association">This is only valid for C-Side associations.</param>
        internal static void AddRule(CommandProcessorContext cpc, Association association)
        {
            Debug.Assert(association != null, "association should not be null");
            Debug.Assert(association.EntityModel.IsCSDL, "association should be from C-side");
            Debug.Assert(
                association.AssociationEnds().Count == 2,
                "association.AssociationEnds().Count(" + association.AssociationEnds().Count + ") should be 2");
            Debug.Assert(association.AssociationSet != null, "association.AssociationSet should not be null");

            IIntegrityCheck check = new InferReferentialConstraints(cpc, association);
            cpc.AddIntegrityCheck(check);
        }
        protected override void InvokeInternal(CommandProcessorContext cpc)
        {
            var service = cpc.EditingContext.GetEFArtifactService();
            var artifact = service.Artifact;

            // the model that we want to add the association to
            var model = artifact.StorageModel();

            // check for uniqueness
            var assocName = Name;
            var assocSetName = assocName;
            if (UniquifyNames)
            {
                assocName = ModelHelper.GetUniqueName(typeof(Association), model, assocName);
                assocSetName = ModelHelper.GetUniqueName(typeof(AssociationSet), model.FirstEntityContainer, assocName);
            }
            else
            {
                // check for uniqueness of the association name
                string msg = null;
                if (ModelHelper.IsUniqueName(typeof(Association), model, assocName, false, out msg) == false)
                {
                    throw new InvalidOperationException(msg);
                }

                // check for uniqueness of the association set name
                if (ModelHelper.IsUniqueName(typeof(AssociationSet), model.FirstEntityContainer, assocSetName, false, out msg) == false)
                {
                    throw new InvalidOperationException(msg);
                }
            }

            // create the new item in our model
            var association = new Association(model, null);
            association.LocalName.Value = assocName;
            model.AddAssociation(association);
            XmlModelHelper.NormalizeAndResolve(association);

            // create the ends of the association
            var fkEnd = new AssociationEnd(association, null);
            fkEnd.Type.SetRefName(FkTable);
            fkEnd.Role.Value = FkRoleNameOverride ?? ModelHelper.CreateFKAssociationEndName(FkTable.LocalName.Value);
            if (FkMultiplicityOverride != null)
            {
                fkEnd.Multiplicity.Value = FkMultiplicityOverride;
            }
            else
            {
                fkEnd.Multiplicity.Value = DoesFkFormPk ? ModelConstants.Multiplicity_ZeroOrOne : ModelConstants.Multiplicity_Many;
            }
            association.AddAssociationEnd(fkEnd);
            XmlModelHelper.NormalizeAndResolve(fkEnd);

            var pkEnd = new AssociationEnd(association, null);
            pkEnd.Type.SetRefName(PkTable);
            pkEnd.Role.Value = PkRoleNameOverride ?? ModelHelper.CreatePKAssociationEndName(PkTable.LocalName.Value);
            if (PkMultiplicityOverride != null)
            {
                pkEnd.Multiplicity.Value = PkMultiplicityOverride;
            }
            else
            {
                pkEnd.Multiplicity.Value = IsNullableFk ? ModelConstants.Multiplicity_ZeroOrOne : ModelConstants.Multiplicity_One;
            }
            association.AddAssociationEnd(pkEnd);
            XmlModelHelper.NormalizeAndResolve(pkEnd);

            var cmd = new CreateAssociationSetCommand(assocSetName, association, ModelSpace.Storage);
            CommandProcessor.InvokeSingleCommand(cpc, cmd);
            var set = cmd.AssociationSet;
            Debug.Assert(set != null, "failed to create an AssociationSet");

            Association = association;
            _createdAssociationFkEnd = fkEnd;
            _createdAssociationPkEnd = pkEnd;
        }
 internal AssociationIdentity GetAssociationIdentity(Association a)
 {
     AssociationIdentity id = null;
     _associationToAssociationIdentity.TryGetValue(a, out id);
     return id;
 }
        internal static IEnumerable<Command> LaunchReferentialConstraintDialog(Association association)
        {
            var commands = new List<Command>();
            if (association != null)
            {
                if (association.ReferentialConstraint == null
                    ||
                    (association.ReferentialConstraint != null &&
                     association.ReferentialConstraint.Principal != null &&
                     association.ReferentialConstraint.Principal.Role.Target != null &&
                     association.ReferentialConstraint.Principal.Role.Target.Type.Target != null &&
                     association.ReferentialConstraint.Dependent != null &&
                     association.ReferentialConstraint.Dependent.Role.Target != null &&
                     association.ReferentialConstraint.Dependent.Role.Target.Type.Target != null
                    )
                    )
                {
                    using (var dlg = new ReferentialConstraintDialog(association))
                    {
                        var result = dlg.ShowDialog();
                        if (result != DialogResult.Cancel
                            && dlg.Principal != null
                            && dlg.Dependent != null)
                        {
                            if (association.ReferentialConstraint != null)
                            {
                                // first, enqueue the delete command (always)
                                commands.Add(association.ReferentialConstraint.GetDeleteCommand());
                            }

                            if (dlg.ShouldDeleteOnly == false)
                            {
                                var principalProps = new List<Property>();
                                var dependentProps = new List<Property>();

                                var keys = GetKeysForType(dlg.Principal.Type.Target);

                                foreach (var mli in dlg.MappingList)
                                {
                                    if (mli.IsValidPrincipalKey)
                                    {
                                        // try to resolve the symbol into a property
                                        Property p = null;
                                        Property d = null;
                                        if (mli.PrincipalKey != null)
                                        {
                                            p = GetKeyForType(mli.PrincipalKey, dlg.Principal.Type.Target, keys);
                                        }

                                        if (mli.DependentProperty != null)
                                        {
                                            d = dlg.Dependent.Artifact.ArtifactSet.LookupSymbol(mli.DependentProperty) as Property;
                                        }

                                        if (p != null
                                            && d != null)
                                        {
                                            principalProps.Add(p);
                                            dependentProps.Add(d);
                                        }
                                    }
                                }

                                // now enqueue the command to create a new one if the user didn't click Delete
                                Debug.Assert(
                                    principalProps.Count == dependentProps.Count,
                                    "principal (" + principalProps.Count + ") & dependent (" + dependentProps.Count
                                    + ") property counts must match!");
                                if (principalProps.Count > 0)
                                {
                                    Command cmd = new CreateReferentialConstraintCommand(
                                        dlg.Principal,
                                        dlg.Dependent,
                                        principalProps,
                                        dependentProps);
                                    commands.Add(cmd);
                                }
                            }
                        }
                    }
                }
                else
                {
                    VsUtils.ShowMessageBox(
                        PackageManager.Package,
                        Resources.Error_CannotEditRefConstraint,
                        OLEMSGBUTTON.OLEMSGBUTTON_OK,
                        OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                        OLEMSGICON.OLEMSGICON_WARNING);
                }
            }
            return commands;
        }
 internal AssociationIdentity GetAssociationIdentityForAssociation(Association assoc)
 {
     var results = _associationSummary.GetAssociationIdentity(assoc);
     return results;
 }
 public ExplorerAssociation(EditingContext context, Association assoc, ExplorerEFElement parent)
     : base(context, assoc, parent)
 {
     // do nothing
 }
        internal ReferentialConstraintDialog(Association association)
        {
            if (association == null)
            {
                // this should never be null on current code-paths.
                throw new ArgumentNullException("association");
            }

            _association = association;
            _end1 = _association.AssociationEnds()[0];
            _end2 = _association.AssociationEnds()[1];

            var selfAssociation = (_end1.Type.Target == _end2.Type.Target);

            _roleListItems.Add(_end1, new RoleListItem(_end1, selfAssociation));
            _roleListItems.Add(_end2, new RoleListItem(_end2, selfAssociation));

            InitializeComponent();

            // enable tool tips
            listMappings.ShowItemToolTips = true;

            if (EdmFeatureManager.GetForeignKeysInModelFeatureState(association.Artifact.SchemaVersion).IsEnabled())
            {
                hdrDepedent.Text = DialogsResource.RefConstraintDialog_DependentKeyHeader_SupportFKs;
            }

            // Set the default font to VS shell font.
            var vsFont = VSHelpers.GetVSFont(Services.ServiceProvider);
            if (vsFont != null)
            {
                Font = vsFont;
            }

            // load list of roles
            cmdPrincipalRole.Items.Add(_blankRoleListItem);
            cmdPrincipalRole.Items.Add(_roleListItems[_end1]);
            cmdPrincipalRole.Items.Add(_roleListItems[_end2]);
        }
        protected override void InvokeInternal(CommandProcessorContext cpc)
        {
            var service = cpc.EditingContext.GetEFArtifactService();
            var artifact = service.Artifact;

            // the model that we want to add the association to
            var model = artifact.ConceptualModel();

            // check for uniqueness of the assocation and association set names
            // if uniquifyNames is true then make them unique, otherwise throw
            // an exception if they're not (always uniquify associationSetName
            // regardless as we get bugs if not)
            var assocName = Name;
            var assocSetName = assocName;
            if (UniquifyNames)
            {
                assocName = ModelHelper.GetUniqueName(typeof(Association), model, assocName);
                assocSetName = ModelHelper.GetUniqueName(typeof(AssociationSet), model.FirstEntityContainer, assocName);

                // ensure unique NavigationProperty names
                if (ShouldCreateNavigationPropertyEnd1
                    && !ModelHelper.IsUniquePropertyName(End1Entity, NavigationPropertyInEnd1Entity, true)
                    || NavigationPropertyInEnd1Entity == End1Entity.LocalName.Value)
                {
                    var namesToAvoid = new HashSet<string>();
                    namesToAvoid.Add(End1Entity.LocalName.Value);
                    namesToAvoid.Add(NavigationPropertyInEnd2Entity);
                    NavigationPropertyInEnd1Entity = ModelHelper.GetUniqueConceptualPropertyName(
                        NavigationPropertyInEnd1Entity, End1Entity, namesToAvoid);
                }

                if (ShouldCreateNavigationPropertyEnd2
                    && !ModelHelper.IsUniquePropertyName(End2Entity, NavigationPropertyInEnd2Entity, true)
                    || NavigationPropertyInEnd2Entity == End2Entity.LocalName.Value)
                {
                    var namesToAvoid = new HashSet<string> { End2Entity.LocalName.Value, NavigationPropertyInEnd1Entity };
                    NavigationPropertyInEnd2Entity = ModelHelper.GetUniqueConceptualPropertyName(
                        NavigationPropertyInEnd2Entity, End2Entity, namesToAvoid);
                }
            }
            else
            {
                assocSetName = ModelHelper.GetUniqueName(typeof(AssociationSet), model.FirstEntityContainer, assocName);

                string msg = null;
                if (!ModelHelper.IsUniqueName(typeof(Association), model, assocName, false, out msg))
                {
                    throw new InvalidOperationException(msg);
                }
                else if (!ModelHelper.IsUniqueName(typeof(AssociationSet), model.FirstEntityContainer, assocSetName, false, out msg))
                {
                    throw new InvalidOperationException(msg);
                }
                else if (ShouldCreateNavigationPropertyEnd1
                         && (!ModelHelper.IsUniquePropertyName(End1Entity, NavigationPropertyInEnd1Entity, true)))
                {
                    msg = string.Format(CultureInfo.CurrentCulture, Resources.NAME_NOT_UNIQUE, NavigationPropertyInEnd1Entity);
                    throw new InvalidOperationException(msg);
                }
                else if (ShouldCreateNavigationPropertyEnd2
                         && (!ModelHelper.IsUniquePropertyName(End2Entity, NavigationPropertyInEnd2Entity, true)))
                {
                    msg = string.Format(CultureInfo.CurrentCulture, Resources.NAME_NOT_UNIQUE, NavigationPropertyInEnd2Entity);
                    throw new InvalidOperationException(msg);
                }
                else if (NavigationPropertyInEnd1Entity == End1Entity.LocalName.Value)
                {
                    msg = string.Format(
                        CultureInfo.CurrentCulture, Resources.NavPropNameSameAsContainer, NavigationPropertyInEnd1Entity);
                    throw new InvalidOperationException(msg);
                }
                else if (NavigationPropertyInEnd2Entity == End2Entity.LocalName.Value)
                {
                    msg = string.Format(
                        CultureInfo.CurrentCulture, Resources.NavPropNameSameAsContainer, NavigationPropertyInEnd2Entity);
                    throw new InvalidOperationException(msg);
                }
            }

            // create the new item in our model
            var association = new Association(model, null);
            association.LocalName.Value = assocName;
            model.AddAssociation(association);
            XmlModelHelper.NormalizeAndResolve(association);

            // create the first end
            _end1 = new AssociationEnd(association, null);
            _end1.Type.SetRefName(End1Entity);
            _end1.Role.Value = End1Entity.LocalName.Value;
            _end1.Multiplicity.Value = End1Multiplicity;
            association.AddAssociationEnd(_end1);
            XmlModelHelper.NormalizeAndResolve(_end1);

            // create the second end
            _end2 = new AssociationEnd(association, null);
            _end2.Type.SetRefName(End2Entity);
            var endRoleValue = End2Entity.LocalName.Value;
            if (_end1.Role.Value.Equals(endRoleValue))
            {
                // avoid duplicate Role values between the two ends. This will occur in self-associations.
                // Appending "1" is consistent with how model-gen chooses a unique name.
                endRoleValue = endRoleValue + "1";
            }
            _end2.Role.Value = endRoleValue;
            _end2.Multiplicity.Value = End2Multiplicity;
            association.AddAssociationEnd(_end2);
            XmlModelHelper.NormalizeAndResolve(_end2);

            // create the association set for this association
            var cmd = new CreateAssociationSetCommand(assocSetName, association);
            CommandProcessor.InvokeSingleCommand(cpc, cmd);
            var set = cmd.AssociationSet;
            Debug.Assert(set != null, "unable to create association set");

            CreateNavigationPropertyCommand navcmd;

            if (ShouldCreateNavigationPropertyEnd1)
            {
                navcmd = new CreateNavigationPropertyCommand(NavigationPropertyInEnd1Entity, End1Entity, association, _end1, _end2);
                CommandProcessor.InvokeSingleCommand(cpc, navcmd);
            }

            if (ShouldCreateNavigationPropertyEnd2)
            {
                navcmd = new CreateNavigationPropertyCommand(NavigationPropertyInEnd2Entity, End2Entity, association, _end2, _end1);
                CommandProcessor.InvokeSingleCommand(cpc, navcmd);
            }

            if (ShouldCreateForeignKeyProperties)
            {
                CreateForeignKeyProperties.AddRule(cpc, association);
            }

            CreatedAssociation = association;
        }
示例#29
0
        private static void InjectAssociationConnectorCommand(
            CommandProcessorContext commandProcessorContext, HashSet<ShapeChangeInformation> shapeChangeInfoSet, Diagram diagram,
            Association association, XObjectChange changeAction)
        {
            // First check to see if there is already a change in the original transaction 
            // for the AssociationConnector that matches the one that we're getting
            var shapeChangeInfoToQuery = new ShapeChangeInformation
                {
                    ChangeType = changeAction,
                    ModelEFObject = association,
                    DiagramId = diagram.Id.Value
                };

            var shapeChangeInfoExists = shapeChangeInfoSet.Contains(shapeChangeInfoToQuery);

            // We only want to create model diagram if the transaction is originated from this diagram.
            if (changeAction == XObjectChange.Add
                && shapeChangeInfoExists == false)
            {
                // The association connector is added if
                // - the participating entities are in the diagram.
                // or
                // - the participating entities will be added in the current transaction.
                foreach (var end in association.AssociationEnds())
                {
                    if (end.Type != null
                        && end.Type.Target != null)
                    {
                        if (diagram.EntityTypeShapes.Where(ets => ets.EntityType.Target == end.Type.Target).Any()
                            || shapeChangeInfoSet.Where(
                                sc =>
                                sc.DiagramId == diagram.Id.Value && sc.ModelEFObject == end.Type.Target
                                && sc.ChangeType == XObjectChange.Add).Any())
                        {
                            continue;
                        }
                    }
                    // If it reach this point, that means that we should not add association connector in the diagram.
                    return;
                }
                var cmd = new CreateAssociationConnectorCommand(diagram, association);
                CommandProcessor.InvokeSingleCommand(commandProcessorContext, cmd);
            }
            else if (changeAction == XObjectChange.Remove
                     && shapeChangeInfoExists == false)
            {
                // this is happening before the transaction is taking place so we are free to look up anti-dependencies on this delete
                foreach (
                    var associationConnector in
                        association.GetAntiDependenciesOfType<AssociationConnector>()
                            .Where(ac => ac.Diagram != null && ac.Diagram.Id == diagram.Id.Value))
                {
                    if (associationConnector != null)
                    {
                        var deleteAssociationConnectorCommand = associationConnector.GetDeleteCommand();
                        CommandProcessor.InvokeSingleCommand(commandProcessorContext, deleteAssociationConnectorCommand);
                    }
                }
            }
        }
        // <summary>
        //     Calls a validation method to check if this association's MSL is editable by the designer
        // </summary>
        internal bool CanEditMappingsForAssociation(Association association, bool allowAssociationMappingEditWithFKs)
        {
            if (association == null)
            {
                throw new ArgumentNullException("association");
            }

            TreeGridDesignerWatermarkInfo watermarkInfo = null;

            if (MappingViewModelHelper.CanEditMappingsForAssociation(
                association, MappingDetailsWindowContainer, ref watermarkInfo, allowAssociationMappingEditWithFKs))
            {
                return true;
            }
            else
            {
                Debug.Assert(watermarkInfo != null, "watermark should not be null");
                if (watermarkInfo != null)
                {
                    SetWatermarkInfo(watermarkInfo);
                }
                return false;
            }
        }