When I was writing the Unit test I got stuck at one point where I saw the code which will create 1:N relationships. But the problem was how to achieve that code in the unit test method? I searched everywhere but did not get a proper solution.
So in this blog, I am going to explain how to write a method for "EntityMetadata: OneToManyRelationshipMetadata".
SDK Reference
- using Microsoft.Xrm.Sdk.Metadata;
- RetrieveEntityRequest request = new RetrieveEntityRequest()
- {
- // Summary: EntityFilters is a ENUM where Relationships value is 8
- // Use this to retrieve entity information plus entity relationships for the entity.
- // Value = 8.
- EntityFilters = EntityFilters.Relationships,
- LogicalName = "account",
- RetrieveAsIfPublished = false,
- };
- RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request);
- if (response.EntityMetadata != null)
- {
- foreach (var relationships in response.EntityMetadata.OneToManyRelationships)
- {
- if (relationships.IsCustomizable.Value)
- {
- var referencingEntity = relationship.ReferencingEntity;
- var referencingAttribute = relationship.ReferencingAttribute;
- /*Your code to implement your logic*/
- ////
- ////
- }
- }
- }
- [TestMethod]
- public void EntityMetadataMethod()
- {
- OrganizationService.ExecuteOrganizationRequest = (request) =>
- {
- // Summary:
- // Defines a managed property that stores a Boolean value.
- // For the Web API the corresponding type is BooleanManagedProperty ComplexType.
- BooleanManagedProperty property = new BooleanManagedProperty()
- {
- Value = true
- };
- // Summary:
- // Contains the metadata for a one-to-many entity relationship.
- OneToManyRelationshipMetadata[] OneToManyRelationships = new OneToManyRelationshipMetadata[]
- {
- new OneToManyRelationshipMetadata()
- {
- ReferencingEntity = "account",
- ReferencingAttribute = "primarycontactid",
- IsCustomizable = property,
- SchemaName = "new_account_contact"
- },
- new OneToManyRelationshipMetadata()
- {
- ReferencingEntity = "contact",
- ReferencingAttribute = "parentaccountid",
- IsCustomizable = property,
- SchemaName = "new_contact_account"
- }
- };
- // Summary:
- // Contains the metadata for an entity.
- EntityMetadata metadata = new EntityMetadata()
- {
- SchemaName = "salesorder"
- };
- metadata.GetType().GetProperty("OneToManyRelationships").SetValue(metadata, OneToManyRelationships);
- OrganizationResponse responce = new RetrieveEntityResponse();
- responce["EntityMetadata"] = metadata;
- return responce;
- };
- }
I hope the above solution will help with your code coverage.
Keep learning new things....!!

Join the conversation! Your thoughts help the community grow.