private void AddManyToMany() { ManyToManyRelationshipMetadata data = new ManyToManyRelationshipMetadata() { SchemaName = Name, Entity1LogicalName = Entity1, Entity2LogicalName = Entity2 }; if (AdvancedFind.HasValue) { data.IsValidForAdvancedFind = AdvancedFind; } if (Customizable.HasValue) { data.IsCustomizable = new BooleanManagedProperty(Customizable.Value); } Guid result = _repository.AddRelationship(data, IntersectName); if (PassThru) { WriteObject(_repository.GetRelationship(result)); } }
public Guid AddRelationship(ManyToManyRelationshipMetadata relationship, string intersect) { bool isEligible1 = EligibleForRelationship(relationship.Entity1LogicalName, "CanManyToMany"); bool isEligible2 = EligibleForRelationship(relationship.Entity2LogicalName, "CanManyToMany"); if (!(isEligible1 && isEligible2)) { throw new Exception(string.Format("Many-to-Many relationship between '{0}' and '{1}' is not allowed.", relationship.Entity1LogicalName, relationship.Entity2LogicalName)); } OrganizationRequest request = new OrganizationRequest("CreateManyToMany") { Parameters = new ParameterCollection { { "IntersectEntitySchemaName", intersect }, { "ManyToManyRelationship", relationship } } }; if (CrmContext.ActiveSolution != null) { request.Parameters.Add("SolutionUniqueName", CrmContext.ActiveSolution); } OrganizationResponse response = CrmContext.OrganizationProxy.Execute(request); return((Guid)response.Results["ManyToManyRelationshipId"]); }
internal static Relationship ToRelationship(ManyToManyRelationshipMetadata metadata) { var schema = new Relationship(); ToRelationship(metadata, schema); return(schema); }
protected static void AddRelationship(ManyToManyRelationshipMetadata relationship, ListViewItem item, List <ListViewItem> sourceAttributesList) { item.SubItems.Add(relationship.IntersectEntityName); item.SubItems.Add(relationship.Entity2LogicalName); item.SubItems.Add(relationship.Entity2IntersectAttribute); sourceAttributesList.Add(item); }
public void SetSealedPropertyValue_should_update_manytomanyrelationship_metadata() { var fakeRelationship = new ManyToManyRelationshipMetadata(); fakeRelationship.SetSealedPropertyValue("Entity2LogicalName", "role"); Assert.Equal("role", fakeRelationship.Entity2LogicalName); }
/// <summary> /// Checks if entity is many to many. /// </summary> /// <param name="intersectEntityName">intersectEntityName.</param> /// <returns>EntityMetadata.IsIntersect or cached value.</returns> public ManyToManyDetails GetManyToManyEntityDetails(string intersectEntityName) { EntityMetadata metadata = GetEntityMetadata(intersectEntityName); bool isIntersect = false; if (metadata.IsIntersect.HasValue) { isIntersect = metadata.IsIntersect.Value; } if (!isIntersect) { return(new ManyToManyDetails() { IsManyToMany = false }); } ManyToManyRelationshipMetadata relationshipDetails = metadata.ManyToManyRelationships.FirstOrDefault(p => p.IntersectEntityName == intersectEntityName); return(new ManyToManyDetails { IsManyToMany = true, SchemaName = relationshipDetails.SchemaName, Entity1IntersectAttribute = relationshipDetails.Entity1IntersectAttribute, Entity1LogicalName = relationshipDetails.Entity1LogicalName, Entity2IntersectAttribute = relationshipDetails.Entity2IntersectAttribute, Entity2LogicalName = relationshipDetails.Entity2LogicalName }); }
public void UpdateCheckBoxesRelationshipNonExistingEntityLogicalName() { string inputEntityLogicalName = "account"; var relationship = new ManyToManyRelationshipMetadata { Entity1LogicalName = "account", Entity1IntersectAttribute = "accountid", IntersectEntityName = "account_contact", Entity2LogicalName = "contact", Entity2IntersectAttribute = "contactid" }; var entityRelationshipSet = new HashSet <string>() { inputEntityLogicalName }; inputEntityRelationships.Add(inputEntityLogicalName, entityRelationshipSet); var item = new System.Windows.Forms.ListViewItem("Item1"); FluentActions.Invoking(() => systemUnderTest.UpdateAttributeMetadataCheckBoxes(relationship.IntersectEntityName, item, inputEntityRelationships, "Random Text")) .Should() .NotThrow(); }
public List <RelatedEntityType> ReadNNRelationship <RelatedEntityType>(string relationshipName, Entity currentEntity, Func <Entity, RelatedEntityType> crmEntityCreater, params string[] relatedColumns) { List <RelatedEntityType> relatedObjects = new List <RelatedEntityType>(); ColumnSet columns = new ColumnSet(relatedColumns); RetrieveRelationshipRequest request = new RetrieveRelationshipRequest() { Name = relationshipName, }; RetrieveRelationshipResponse response = (RetrieveRelationshipResponse)Connection.Service.Execute(request); ManyToManyRelationshipMetadata metaData = (ManyToManyRelationshipMetadata)response.Results["RelationshipMetadata"]; KeyValuePair <EntityRelationshipInfo, EntityRelationshipInfo> relationshipInfo = EntityRelationshipInfo.GetFromMetaData(currentEntity.LogicalName, metaData); List <Guid> relatedIds = GetRelatedIds(currentEntity.Id, metaData.IntersectEntityName, relationshipInfo.Key.IntersectAttribute, relationshipInfo.Value.IntersectAttribute); foreach (Guid entityId in relatedIds) { Entity relatedEntity = Connection.Service.Retrieve(relationshipInfo.Value.LogicalName, entityId, columns); RelatedEntityType relatedObject = crmEntityCreater(relatedEntity); relatedObjects.Add(relatedObject); } return(relatedObjects); }
public RelationRecord(ManyToManyRelationshipMetadata relation, TransferMode mode, BackgroundWorker worker, IOrganizationService sourceService, IOrganizationService targetService) { if (sourceEntitiesMetadata == null) { sourceEntitiesMetadata = new List <ManyToManyRelationshipMetadata>(); } if (targetEntitiesMetadata == null) { targetEntitiesMetadata = new List <ManyToManyRelationshipMetadata>(); } if (targetCurrentUserId == Guid.Empty) { targetCurrentUserId = ((WhoAmIResponse)targetService.Execute(new WhoAmIRequest())).UserId; } this.worker = worker; this.relation = relation; this.transfermode = mode; this.sourceService = sourceService; this.targetService = targetService; this.Name = relation.SchemaName; this.Messages = new List <string>(); }
public ManyToManyRelationshipComponent(ManyToManyRelationshipMetadata mtmmd) { this.mtmmd = mtmmd; Id = mtmmd.MetadataId; ComponentType = EnumTypes.ComponentType.Relationship; Name = mtmmd.SchemaName; DisplayName = Name; }
private ManyToManyRelationshipMetadata GetMetadata() { if (_sdkMetadata == null) { _sdkMetadata = XrmService.GetManyToManyRelationship(_recordTypeForLoading, SchemaName);; } return(_sdkMetadata); }
public static void purgeExistingRelationships(ManyToManyRelationshipMetadata metaData, IOrganizationService orgService, ILog logger) { logger.Info(string.Format("Purging existing record associations for relationship {0}", metaData.SchemaName)); //use metadata to create a qry to retreive all records in the N:N table. var qry = new QueryExpression { EntityName = metaData.IntersectEntityName, ColumnSet = new ColumnSet( metaData.Entity1IntersectAttribute, metaData.Entity2IntersectAttribute) }; var existingRelationships = orgService.RetrieveMultiple(qry).Entities; logger.Info(string.Format("Found {0} existing relationships", existingRelationships.Count)); //remove each existing association foreach (var record in existingRelationships) { var entity1Id = new EntityReference(metaData.Entity1LogicalName, record.GetAttributeValue <Guid>(metaData.Entity1IntersectAttribute)); var entity2Id = new EntityReference(metaData.Entity2LogicalName, record.GetAttributeValue <Guid>(metaData.Entity2IntersectAttribute)); var req = new DisassociateRequest { Relationship = new Relationship(metaData.SchemaName), Target = entity1Id, RelatedEntities = new EntityReferenceCollection { entity2Id } }; if (entity1Id.LogicalName == entity2Id.LogicalName) { req.Relationship.PrimaryEntityRole = EntityRole.Referenced; } logger.Info(string.Format("Removing link between {0}-{1} and {2}-{3}", entity1Id.LogicalName, entity1Id.Id, entity2Id.LogicalName, entity2Id.Id)); orgService.Execute(req); req = new DisassociateRequest { Relationship = new Relationship(metaData.SchemaName), Target = entity2Id, RelatedEntities = new EntityReferenceCollection { entity1Id } }; if (entity1Id.LogicalName == entity2Id.LogicalName) { req.Relationship.PrimaryEntityRole = EntityRole.Referenced; } logger.Info(string.Format("Removing link between {2}-{3} and {0}-{1}", entity1Id.LogicalName, entity1Id.Id, entity2Id.LogicalName, entity2Id.Id)); orgService.Execute(req); } }
internal static void ToRelationship(ManyToManyRelationshipMetadata metadata, Relationship schema) { Log.Silently($"Copying metadata for relationship {metadata.SchemaName}."); schema.IsReflexive = metadata.Entity1LogicalName == metadata.Entity2LogicalName; schema.Name = metadata.IntersectEntityName; // CMT doesn't capture SchemaName - but probably should. schema.RelatedEntity = metadata.IntersectEntityName; schema.TargetEntity = metadata.Entity2LogicalName; schema.TargetEntityPrimaryKey = metadata.Entity2IntersectAttribute; }
private static RelationshipDto GetRelationshipDto(string entityLogicalName, ManyToManyRelationshipMetadata relationshipMetadata) { var relationLogicalName = relationshipMetadata.SchemaName; var itemSetEntityLogicalName = relationshipMetadata.Entity1LogicalName.Equals(entityLogicalName, StringComparison.InvariantCultureIgnoreCase) ? relationshipMetadata.Entity2LogicalName : relationshipMetadata.Entity1LogicalName; return(new RelationshipDto { Relationship = relationLogicalName, ItemSetEntity = itemSetEntityLogicalName }); }
public void StoreCrmEntityRelationShipData(CrmEntity crmEntity, ManyToManyRelationshipMetadata relationship, List <CrmRelationship> relationshipList) { var crmRelationShip = new CrmRelationship { RelatedEntityName = relationship.IntersectEntityName, ManyToMany = true, IsReflexive = relationship.IsCustomizable.Value, TargetEntityPrimaryKey = crmEntity.PrimaryIdField == relationship.Entity2IntersectAttribute ? relationship.Entity1IntersectAttribute : relationship.Entity2IntersectAttribute, TargetEntityName = crmEntity.Name == relationship.Entity2LogicalName ? relationship.Entity1LogicalName : relationship.Entity2LogicalName, RelationshipName = relationship.IntersectEntityName }; relationshipList.Add(crmRelationShip); }
public static MappingRelationshipMN Parse(ManyToManyRelationshipMetadata rel, string thisEntityLogicalName) { var result = new MappingRelationshipMN(); if (rel.Entity1LogicalName == thisEntityLogicalName) { result.Attribute = new CrmRelationshipAttribute { FromEntity = rel.Entity1LogicalName, FromKey = rel.Entity1IntersectAttribute, ToEntity = rel.Entity2LogicalName, ToKey = rel.Entity2IntersectAttribute, IntersectingEntity = rel.IntersectEntityName }; } else { result.Attribute = new CrmRelationshipAttribute { ToEntity = rel.Entity1LogicalName, ToKey = rel.Entity1IntersectAttribute, FromEntity = rel.Entity2LogicalName, FromKey = rel.Entity2IntersectAttribute, IntersectingEntity = rel.IntersectEntityName }; } result.EntityRole = "null"; result.SchemaName = Naming.GetProperVariableName(rel.SchemaName); result.DisplayName = Naming.GetProperVariableName(rel.SchemaName); if (rel.Entity1LogicalName == rel.Entity2LogicalName && rel.Entity1LogicalName == thisEntityLogicalName) { result.DisplayName = "Referenced" + result.DisplayName; result.EntityRole = "Microsoft.Xrm.Sdk.EntityRole.Referenced"; result.IsSelfReferenced = true; } if (result.DisplayName == thisEntityLogicalName) { result.DisplayName += "1"; // this is what CrmSvcUtil does } result.HybridName = Naming.GetProperVariableName(rel.SchemaName) + "_NN"; result.PrivateName = "_nn" + Naming.GetEntityPropertyPrivateName(rel.SchemaName); result.ForeignKey = Naming.GetProperVariableName(result.Attribute.ToKey); result.Type = Naming.GetProperVariableName(result.Attribute.ToEntity); result.MetadataId = rel.MetadataId; return(result); }
public void GetNameForRelationship_ManyToMany() { organizationMetadata.Entities.Returns(new[] { new EntityMetadata { LogicalName = "ee_testprop", DisplayCollectionName = new Label("Test Props", 1033) } .Set(x => x.Attributes, new AttributeMetadata[] { new StringAttributeMetadata { LogicalName = "ee_testid", DisplayName = "Test Id".AsLabel() } }) }); var relationship = new OneToManyRelationshipMetadata { ReferencingEntity = "ee_testprop", ReferencingAttribute = "ee_testid", ReferencedEntity = "ee_test", SchemaName = "ee_two" }; var many2Many = new ManyToManyRelationshipMetadata { Entity1LogicalName = "ee_test", Entity2LogicalName = "ee_testprop", SchemaName = "ee_testProp_association" }; var attMetadata = new StringAttributeMetadata { LogicalName = "ee_testid", DisplayName = "Test Id".AsLabel() }; var metadata = new EntityMetadata { LogicalName = "ee_test" } .Set(x => x.Attributes, new AttributeMetadata[] { attMetadata }) .Set(x => x.OneToManyRelationships, new OneToManyRelationshipMetadata[] { relationship, new OneToManyRelationshipMetadata { ReferencingEntity = "ee_testprop", ReferencingAttribute = "ee_testid", SchemaName = "ee_one" } }) .Set(x => x.ManyToManyRelationships, new[] { many2Many }); var output = sut.GetNameForRelationship(metadata, many2Many, null, serviceProvider); Assert.AreEqual("TestProps", output); }
public static EntityCollection RetrieveManyToManyRelationship(EntityReference entityReference, string schemaName, IOrganizationService organizationService) { EntityCollection entityCollection = null; //Null validation if (entityReference != null) { //Get many to many metadata from entity metadata where schema name meets criteria ManyToManyRelationshipMetadata manyToManyRelationshipMetadata = RetrieveManyToManyRelationshipMetadata(entityReference.LogicalName, schemaName, organizationService); entityCollection = RetrieveManyToManyRelationship(entityReference, manyToManyRelationshipMetadata, organizationService); } return(entityCollection); }
public bool QueryManyToManyRelationship() { RetrieveRelationshipRequest request = new RetrieveRelationshipRequest(); request.Name = "accountleads_association"; request.RetrieveAsIfPublished = true; RetrieveRelationshipResponse response = (RetrieveRelationshipResponse)OrganizationServiceProxy.Execute(request); ManyToManyRelationshipMetadata relationship = (ManyToManyRelationshipMetadata)response.RelationshipMetadata; Assert.AreEqual(relationship.IsCustomRelationship, false); Assert.AreEqual(relationship.SchemaName, "accountleads_association"); Assert.AreEqual(relationship.IntersectEntityName, "accountleads"); return(true); }
public static ManyToManyRelationshipMetadata RetrieveManyToManyRelationshipMetadata(string logicalName, string schemaName, IOrganizationService organizationService) { ManyToManyRelationshipMetadata manyToManyRelationshipMetadata = null; EntityMetadata entityMetadata = RetrieveEntityMetadata(logicalName, EntityFilters.Relationships, organizationService); //Null validation if (entityMetadata != null) { //Get many to many relationship metadata manyToManyRelationshipMetadata = entityMetadata.ManyToManyRelationships.FirstOrDefault(item => !string.IsNullOrEmpty(item.SchemaName) && item.SchemaName.ToLowerInvariant().Equals(schemaName.ToLowerInvariant())); } return(manyToManyRelationshipMetadata); }
public static MappingRelationshipN1 Parse(ManyToManyRelationshipMetadata rel) { return(new MappingRelationshipN1 { Attribute = new CDSRelationshipAttribute { //FromEntity = rel.ReferencedEntity, //FromKey = rel.ReferencedAttribute, //ToEntity = rel.ReferencingEntity, //ToKey = rel.ReferencingAttribute, IntersectingEntity = rel.IntersectEntityName }, DisplayName = Helper.GetProperVariableName(rel.SchemaName), PrivateName = "_nn" + Helper.GetEntityPropertyPrivateName(rel.SchemaName) }); }
private List <string> GetDifferenceManyToMany(ManyToManyRelationshipMetadata rel1, ManyToManyRelationshipMetadata rel2) { var table = new FormatTextTableHandler(true); table.SetHeader("Property", _connectionName1, _connectionName2); AddAssociatedMenuConfigurationDifference(table, "Entity1AssociatedMenuConfiguration", rel1.Entity1AssociatedMenuConfiguration, rel2.Entity1AssociatedMenuConfiguration); AddAssociatedMenuConfigurationDifference(table, "Entity2AssociatedMenuConfiguration", rel1.Entity2AssociatedMenuConfiguration, rel2.Entity2AssociatedMenuConfiguration); List <string> result = new List <string>(); if (table.Count > 0) { result.AddRange(table.GetFormatedLines(false)); } return(result); }
public void PopulateRelationshipAction() { string entityLogicalName = "account_contact"; var items = new List <System.Windows.Forms.ListViewItem> { new System.Windows.Forms.ListViewItem("Item1"), new System.Windows.Forms.ListViewItem("Item2") }; var entityMetadata = new EntityMetadata(); var relationship = new ManyToManyRelationshipMetadata { Entity1LogicalName = "account", Entity1IntersectAttribute = "accountid", IntersectEntityName = "account_contact", Entity2LogicalName = "contact", Entity2IntersectAttribute = "contactid" }; InsertManyToManyRelationshipMetadata(entityMetadata, relationship); var migratorServiceParameters = GenerateMigratorParameters(); MetadataServiceMock.Setup(x => x.RetrieveEntities(It.IsAny <string>(), It.IsAny <IOrganizationService>(), It.IsAny <IExceptionService>())) .Returns(entityMetadata) .Verifiable(); using (var listView = new System.Windows.Forms.ListView()) { var controller = new EntityController(); controller.PopulateEntitiesListView(items, null, null, listView, NotificationServiceMock.Object); var actual = systemUnderTest.PopulateRelationshipAction(entityLogicalName, inputEntityRelationships, migratorServiceParameters); actual.Count.Should().BeGreaterThan(0); } ServiceMock.VerifyAll(); MetadataServiceMock.VerifyAll(); }
public RecordsListerControl(List <Entity> records, List <Entity> allRecords, ManyToManyRelationshipMetadata mm, List <EntityMetadata> emds) { InitializeComponent(); lvRecords.ListViewItemSorter = new ListViewItemComparer(); foreach (var record in records) { var e1 = mm.Entity1LogicalName; var id1 = record.GetAttributeValue <Guid>(mm.Entity1IntersectAttribute); var emd1 = emds.First(e => e.LogicalName == e1); var name1 = allRecords.FirstOrDefault(r => r.LogicalName == e1 && r.Id == id1)?.GetAttributeValue <string>(emd1.PrimaryNameAttribute) ?? id1.ToString("B"); var e2 = mm.Entity2LogicalName; var id2 = record.GetAttributeValue <Guid>(mm.Entity2IntersectAttribute); var emd2 = emds.First(e => e.LogicalName == e2); var name2 = allRecords.FirstOrDefault(r => r.LogicalName == e2 && r.Id == id2)?.GetAttributeValue <string>(emd2.PrimaryNameAttribute) ?? id2.ToString("B");; if (lvRecords.Columns.Count == 0) { lvRecords.Columns.Add(new ColumnHeader { Text = emd1.DisplayName?.UserLocalizedLabel?.Label ?? emd1.SchemaName }); lvRecords.Columns.Add(new ColumnHeader { Text = emd2.DisplayName?.UserLocalizedLabel?.Label ?? emd2.SchemaName }); } var item = new ListViewItem(name1) { Tag = record, SubItems = { name2 }, Checked = true }; lvRecords.Items.Add(item); } }
public void CollectCrmEntityRelationShipWithInputEntityRelationships() { var entityLogicalName = "contact"; var intersectEntityName = "account_contact"; var relationship = new ManyToManyRelationshipMetadata { Entity1LogicalName = "account", Entity1IntersectAttribute = "accountid", IntersectEntityName = intersectEntityName, Entity2LogicalName = "contact", Entity2IntersectAttribute = "contactid", IsCustomizable = new BooleanManagedProperty() { Value = true } }; var entityRelationshipSet = new HashSet <string>() { intersectEntityName }; inputEntityRelationships.Add(entityLogicalName, entityRelationshipSet); var entityMetadata = InstantiateEntityMetaData(entityLogicalName); InsertAttributeList(entityMetadata, new List <string> { "contactId", "firstname", "lastname" }); InsertManyToManyRelationshipMetadata(entityMetadata, relationship); var crmEntity = new Capgemini.Xrm.DataMigration.Model.CrmEntity(); FluentActions.Invoking(() => systemUnderTest.CollectCrmEntityRelationShip(entityMetadata, crmEntity, inputEntityRelationships)) .Should() .NotThrow(); crmEntity.CrmRelationships.Count.Should().Be(1); }
public void LoadData(ManyToManyRelationshipMetadata item) { if (item.MetadataId.HasValue) { this.MetadataId = item.MetadataId; } if (!string.IsNullOrEmpty(item.SchemaName)) { this.SchemaName = item.SchemaName; } if (!string.IsNullOrEmpty(item.IntersectEntityName)) { this.IntersectEntityName = item.IntersectEntityName; } if (!string.IsNullOrEmpty(item.Entity1LogicalName)) { this.Entity1Name = item.Entity1LogicalName; } if (!string.IsNullOrEmpty(item.Entity2LogicalName)) { this.Entity2Name = item.Entity2LogicalName; } if (!string.IsNullOrEmpty(item.Entity1IntersectAttribute)) { this.Entity1IntersectAttributeName = item.Entity1IntersectAttribute; } if (!string.IsNullOrEmpty(item.Entity2IntersectAttribute)) { this.Entity2IntersectAttributeName = item.Entity2IntersectAttribute; } }
public void StoreCrmEntityRelationShipData() { var entityLogicalName = "contact"; var intersectEntityName = "account_contact"; var relationship = new ManyToManyRelationshipMetadata { Entity1LogicalName = "account", Entity1IntersectAttribute = "accountid", IntersectEntityName = intersectEntityName, Entity2LogicalName = "contact", Entity2IntersectAttribute = "contactid", IsCustomizable = new BooleanManagedProperty() { Value = true } }; var relationshipList = new List <Capgemini.Xrm.DataMigration.Model.CrmRelationship>(); var crmEntity = new Capgemini.Xrm.DataMigration.Model.CrmEntity { Name = entityLogicalName, DisplayName = entityLogicalName }; FluentActions.Invoking(() => systemUnderTest.StoreCrmEntityRelationShipData(crmEntity, relationship, relationshipList)) .Should() .NotThrow(); relationshipList.Count.Should().Be(1); relationshipList[0].RelatedEntityName.Should().Be(relationship.IntersectEntityName); relationshipList[0].RelationshipName.Should().Be(relationship.IntersectEntityName); relationshipList[0].IsReflexive.Should().Be(relationship.IsCustomizable.Value); relationshipList[0].ManyToMany.Should().BeTrue(); }
public void GetManyToManyEntityDetails() { string intersectEntityName = "accountcontactmtmed"; var relationship = new ManyToManyRelationshipMetadata { IntersectEntityName = intersectEntityName }; var manyToManyRelationships = new List <ManyToManyRelationshipMetadata> { relationship }; RetrieveEntityResponse response = InjectMetaDataToResponse(new RetrieveEntityResponse(), null, null, manyToManyRelationships, true); MockOrganizationService.Setup(a => a.Execute(It.IsAny <OrganizationRequest>())).Returns(response); FluentActions.Invoking(() => systemUnderTest.GetManyToManyEntityDetails(intersectEntityName)) .Should() .NotThrow(); MockOrganizationService.VerifyAll(); }
public static MappingRelationshipMN Parse(ManyToManyRelationshipMetadata rel, MappingRelationshipMN relationshipManyToMany, string thisEntityLogicalName) { relationshipManyToMany ??= new MappingRelationshipMN(); if (rel.Entity1LogicalName != null) { if (rel.Entity1LogicalName == thisEntityLogicalName) { relationshipManyToMany.Attribute ??= new CrmRelationshipAttribute(); relationshipManyToMany.Attribute.FromEntity = rel.Entity1LogicalName ?? relationshipManyToMany.Attribute.FromEntity; relationshipManyToMany.Attribute.FromKey = rel.Entity1IntersectAttribute ?? relationshipManyToMany.Attribute.FromKey; relationshipManyToMany.Attribute.ToEntity = rel.Entity2LogicalName ?? relationshipManyToMany.Attribute.ToEntity; relationshipManyToMany.Attribute.ToKey = rel.Entity2IntersectAttribute ?? relationshipManyToMany.Attribute.ToKey; } else { relationshipManyToMany.Attribute ??= new CrmRelationshipAttribute(); relationshipManyToMany.Attribute.ToEntity = rel.Entity1LogicalName ?? relationshipManyToMany.Attribute.ToEntity; relationshipManyToMany.Attribute.ToKey = rel.Entity1IntersectAttribute ?? relationshipManyToMany.Attribute.ToKey; relationshipManyToMany.Attribute.FromEntity = rel.Entity2LogicalName ?? relationshipManyToMany.Attribute.FromEntity; relationshipManyToMany.Attribute.FromKey = rel.Entity2IntersectAttribute ?? relationshipManyToMany.Attribute.FromKey; } relationshipManyToMany.Attribute.IntersectingEntity = rel.IntersectEntityName ?? relationshipManyToMany.Attribute.IntersectingEntity; } relationshipManyToMany.EntityRole = "null"; if (rel.SchemaName != null) { relationshipManyToMany.SchemaName = rel.SchemaName; relationshipManyToMany.DisplayName = rel.SchemaName; relationshipManyToMany.HybridName = Naming.GetProperVariableName(rel.SchemaName, false) + "_NN"; relationshipManyToMany.PrivateName = "_nn" + Naming.GetEntityPropertyPrivateName(rel.SchemaName); } if (rel.Entity1LogicalName != null && rel.Entity2LogicalName != null && rel.Entity1LogicalName == rel.Entity2LogicalName && rel.Entity1LogicalName == thisEntityLogicalName) { relationshipManyToMany.DisplayName = "Referenced_" + relationshipManyToMany.DisplayName; relationshipManyToMany.EntityRole = "Microsoft.Xrm.Sdk.EntityRole.Referenced"; relationshipManyToMany.IsSelfReferenced = true; } if (relationshipManyToMany.DisplayName == thisEntityLogicalName) { relationshipManyToMany.DisplayName += "1"; // this is what CrmSvcUtil does } relationshipManyToMany.ForeignKey = Naming.GetProperVariableName(relationshipManyToMany.Attribute.ToKey, false); relationshipManyToMany.Type = relationshipManyToMany.Attribute.ToEntity; relationshipManyToMany.MetadataId = rel.MetadataId; return(relationshipManyToMany); }
public static IEnumerable <EntityMetadata> FromEarlyBoundEntities(Assembly earlyBoundEntitiesAssembly) { List <EntityMetadata> entityMetadatas = new List <EntityMetadata>(); foreach (var earlyBoundEntity in earlyBoundEntitiesAssembly.GetTypes()) { EntityLogicalNameAttribute entityLogicalNameAttribute = GetCustomAttribute <EntityLogicalNameAttribute>(earlyBoundEntity); if (entityLogicalNameAttribute == null) { continue; } EntityMetadata metadata = new EntityMetadata(); metadata.LogicalName = entityLogicalNameAttribute.LogicalName; FieldInfo entityTypeCode = earlyBoundEntity.GetField("EntityTypeCode", BindingFlags.Static | BindingFlags.Public); if (entityTypeCode != null) { metadata.SetFieldValue("_objectTypeCode", entityTypeCode.GetValue(null)); } List <AttributeMetadata> attributeMetadatas = new List <AttributeMetadata>(); List <ManyToManyRelationshipMetadata> manyToManyRelationshipMetadatas = new List <ManyToManyRelationshipMetadata>(); List <OneToManyRelationshipMetadata> oneToManyRelationshipMetadatas = new List <OneToManyRelationshipMetadata>(); List <OneToManyRelationshipMetadata> manyToOneRelationshipMetadatas = new List <OneToManyRelationshipMetadata>(); var idProperty = earlyBoundEntity.GetProperty("Id"); AttributeLogicalNameAttribute attributeLogicalNameAttribute; if (idProperty != null && (attributeLogicalNameAttribute = GetCustomAttribute <AttributeLogicalNameAttribute>(idProperty)) != null) { metadata.SetFieldValue("_primaryIdAttribute", attributeLogicalNameAttribute.LogicalName); } var properties = earlyBoundEntity.GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(x => x.Name != "Id" && Attribute.IsDefined(x, typeof(AttributeLogicalNameAttribute)) || Attribute.IsDefined(x, typeof(RelationshipSchemaNameAttribute))); foreach (var property in properties) { RelationshipSchemaNameAttribute relationshipSchemaNameAttribute = GetCustomAttribute <RelationshipSchemaNameAttribute>(property); attributeLogicalNameAttribute = GetCustomAttribute <AttributeLogicalNameAttribute>(property); if (relationshipSchemaNameAttribute == null) { #if !FAKE_XRM_EASY if (property.PropertyType == typeof(byte[])) { metadata.SetFieldValue("_primaryImageAttribute", attributeLogicalNameAttribute.LogicalName); } #endif AttributeMetadata attributeMetadata; if (attributeLogicalNameAttribute.LogicalName == "statecode") { attributeMetadata = new StateAttributeMetadata(); } else if (attributeLogicalNameAttribute.LogicalName == "statuscode") { attributeMetadata = new StatusAttributeMetadata(); } else if (attributeLogicalNameAttribute.LogicalName == metadata.PrimaryIdAttribute) { attributeMetadata = new AttributeMetadata(); attributeMetadata.SetSealedPropertyValue("AttributeType", AttributeTypeCode.Uniqueidentifier); } else { attributeMetadata = CreateAttributeMetadata(property.PropertyType); } attributeMetadata.SetFieldValue("_entityLogicalName", entityLogicalNameAttribute.LogicalName); attributeMetadata.SetFieldValue("_logicalName", attributeLogicalNameAttribute.LogicalName); attributeMetadatas.Add(attributeMetadata); } else { if (property.PropertyType.Name == "IEnumerable`1") { PropertyInfo peerProperty = property.PropertyType.GetGenericArguments()[0].GetProperties().SingleOrDefault(x => x.PropertyType == earlyBoundEntity && GetCustomAttribute <RelationshipSchemaNameAttribute>(x)?.SchemaName == relationshipSchemaNameAttribute.SchemaName); if (peerProperty == null || peerProperty.PropertyType.Name == "IEnumerable`1") // N:N relationship { ManyToManyRelationshipMetadata relationshipMetadata = new ManyToManyRelationshipMetadata(); relationshipMetadata.SchemaName = relationshipSchemaNameAttribute.SchemaName; manyToManyRelationshipMetadatas.Add(relationshipMetadata); } else // 1:N relationship { AddOneToManyRelationshipMetadata(earlyBoundEntity, property, property.PropertyType.GetGenericArguments()[0], peerProperty, oneToManyRelationshipMetadatas); } } else //N:1 Property { AddOneToManyRelationshipMetadata(property.PropertyType, property.PropertyType.GetProperties().SingleOrDefault(x => x.PropertyType.GetGenericArguments().SingleOrDefault() == earlyBoundEntity && GetCustomAttribute <RelationshipSchemaNameAttribute>(x)?.SchemaName == relationshipSchemaNameAttribute.SchemaName), earlyBoundEntity, property, manyToOneRelationshipMetadatas); } } } if (attributeMetadatas.Any()) { metadata.SetSealedPropertyValue("Attributes", attributeMetadatas.ToArray()); } if (manyToManyRelationshipMetadatas.Any()) { metadata.SetSealedPropertyValue("ManyToManyRelationships", manyToManyRelationshipMetadatas.ToArray()); } if (manyToOneRelationshipMetadatas.Any()) { metadata.SetSealedPropertyValue("ManyToOneRelationships", manyToOneRelationshipMetadatas.ToArray()); } if (oneToManyRelationshipMetadatas.Any()) { metadata.SetSealedPropertyValue("OneToManyRelationships", oneToManyRelationshipMetadatas.ToArray()); } entityMetadatas.Add(metadata); } return(entityMetadatas); }
static CodeTypeMember BuildManyToMany(EntityMetadata entity, EntityMetadata otherEntity, ManyToManyRelationshipMetadata manyToMany, string propertyName, EntityRole? entityRole, ServiceProvider serviceProvider) { Trace.TraceInformation("Entering {0}", new object[] {MethodBase.GetCurrentMethod().Name}); var typeParameter = serviceProvider.TypeMappingService.GetTypeForRelationship(manyToMany, otherEntity, serviceProvider); var property = PropertyGet(IEnumerable(typeParameter), propertyName, new CodeStatement[0]); property.GetStatements.Add(BuildRelationshipGet("GetRelatedEntities", manyToMany, typeParameter, entityRole)); property.SetStatements.AddRange(BuildRelationshipSet("SetRelatedEntities", manyToMany, typeParameter, entityRole)); property.CustomAttributes.Add(BuildRelationshipSchemaNameAttribute(manyToMany.SchemaName, entityRole)); property.Comments.AddRange(CommentSummary("N:N " + manyToMany.SchemaName)); Trace.TraceInformation("Exiting {0}: {1}.ManyToMany {2} defined", new object[] {MethodBase.GetCurrentMethod().Name, entity.LogicalName, propertyName}); return property; }
public ManyToManyRelationshipMetadataInfo(ManyToManyRelationshipMetadata mtmmd) { this.mtmmd = mtmmd; }
public void CreateOrUpdateRelationship(string schemaName, string entityType1, string entityType2, bool entityType1DisplayRelated, bool entityType2DisplayRelated) { var metadata = new ManyToManyRelationshipMetadata(); lock (LockObject) { var exists = RelationshipExists(schemaName); if (exists) metadata = GetRelationshipMetadata(schemaName); metadata.SchemaName = schemaName; metadata.IntersectEntityName = schemaName; metadata.Entity1LogicalName = entityType1; metadata.Entity2LogicalName = entityType2; metadata.Entity1AssociatedMenuConfiguration = new AssociatedMenuConfiguration() { Behavior = entityType1DisplayRelated ? AssociatedMenuBehavior.UseCollectionName : AssociatedMenuBehavior.DoNotDisplay }; metadata.Entity2AssociatedMenuConfiguration = new AssociatedMenuConfiguration() { Behavior = entityType2DisplayRelated ? AssociatedMenuBehavior.UseCollectionName : AssociatedMenuBehavior.DoNotDisplay }; if (exists) { var request = new UpdateRelationshipRequest { Relationship = metadata }; Execute(request); } else { var request = new CreateManyToManyRequest { IntersectEntitySchemaName = schemaName, ManyToManyRelationship = metadata }; Execute(request); } RefreshRelationshipMetadata(schemaName); } }