您可以通过 UI 转到实体 N:N 关系来建立 N:N 关系。与中间实体进行 2 N:1 关系比进行单个 N:N 具有优势,例如您可以存储关系属性(关系的角色),并且您可以通过双重 N:1 关系链接工作流。
编辑:
要通过代码创建 N:N 关系,您可以参考 CRM 2011 SDK 帮助页面“创建和检索实体关系”,摘录如下。您将能够通过 4.0 中的元数据服务做类似的事情 -
创建 N:N 实体关系
以下示例使用 EligibleCreateManyToManyRelationship 方法验证 Account 和 Campaign 实体是否可以参与 N:N 实体关系,然后使用 CreateManyToManyRequest 创建实体关系。
bool accountEligibleParticipate =
EligibleCreateManyToManyRelationship("account");
bool campaignEligibleParticipate =
EligibleCreateManyToManyRelationship("campaign");
if (accountEligibleParticipate && campaignEligibleParticipate)
{
CreateManyToManyRequest createManyToManyRelationshipRequest =
new CreateManyToManyRequest
{
IntersectEntitySchemaName = "new_accounts_campaigns",
ManyToManyRelationship = new ManyToManyRelationshipMetadata
{
SchemaName = "new_accounts_campaigns",
Entity1LogicalName = "account",
Entity1AssociatedMenuConfiguration =
new AssociatedMenuConfiguration
{
Behavior = AssociatedMenuBehavior.UseLabel,
Group = AssociatedMenuGroup.Details,
Label = new Label("Account", 1033),
Order = 10000
},
Entity2LogicalName = "campaign",
Entity2AssociatedMenuConfiguration =
new AssociatedMenuConfiguration
{
Behavior = AssociatedMenuBehavior.UseLabel,
Group = AssociatedMenuGroup.Details,
Label = new Label("Campaign", 1033),
Order = 10000
}
}
};
CreateManyToManyResponse createManytoManyRelationshipResponse =
(CreateManyToManyResponse)_serviceProxy.Execute(
createManyToManyRelationshipRequest);
_manyToManyRelationshipId =
createManytoManyRelationshipResponse.ManyToManyRelationshipId;
_manyToManyRelationshipName =
createManyToManyRelationshipRequest.ManyToManyRelationship.SchemaName;
Console.WriteLine(
"The many-to-many relationship has been created between {0} and {1}.",
"account", "campaign");
}
EligibleCreateManyToManyRelationship
以下示例创建一个 EligibleCreateManyToManyRelationship 方法,该方法使用 CanManyToManyRequest 来验证实体是否可以参与 N:N 实体关系。
/// <summary>
/// Determines whether the entity can participate in a many-to-many relationship.
/// </summary>
/// <param name="entity">Entity</param>
/// <returns></returns>
public bool EligibleCreateManyToManyRelationship(string entity)
{
CanManyToManyRequest canManyToManyRequest = new CanManyToManyRequest
{
EntityName = entity
};
CanManyToManyResponse canManyToManyResponse =
(CanManyToManyResponse)_serviceProxy.Execute(canManyToManyRequest);
if (!canManyToManyResponse.CanManyToMany)
{
Console.WriteLine(
"Entity {0} can't participate in a many-to-many relationship.",
entity);
}
return canManyToManyResponse.CanManyToMany;
}