当我将注释链接到特定实体时,而不是像这样创建关系:
var associateRequest = new AssociateRequest
{
Target = new EntityReference(SalesOrder.EntityLogicalName, salesOrderGuid),
RelatedEntities = new EntityReferenceCollection
{
new EntityReference(Annotation.EntityLogicalName, noteGuid),
},
Relationship = new Relationship("SalesOrder_Annotation")
};
是否可以以强类型方式引用关系:
var associateRequest = new AssociateRequest
{
Target = new EntityReference(SalesOrder.EntityLogicalName, salesOrderGuid),
RelatedEntities = new EntityReferenceCollection
{
new EntityReference(Annotation.EntityLogicalName, noteGuid)
},
Relationship = SalesOrder.Relationships.SalesOrder_Annotation // <----- ???
};
这类似于能够在开发时获取逻辑名:
SalesOrder.EntityLogicalName
我们能否以相同的方式引用特定的1:N关系:
SalesOrder.Relationships.SalesOrder_Annotation
最佳答案
如果您使用SDK中提供的标准RelationshipSchemaNameAttribute
应用程序(CrmSvcUtil.exe
)生成代码,则所要查找的值存储在code属性\SDK\Bin\CrmSvcUtil.exe
中。我已经使用SDK中提供的早期绑定(bind)实体类文件(\SDK\SampleCode\CS\HelperCode\MyOrganizationCrmSdkTypes.cs
)在控制台应用程序中验证了此代码。
调用方法如下(根据您的示例):var relationship = GetRelationship<SalesOrder>(nameof(SalesOrder.SalesOrder_Annotation))
或者,如果您想返回实际的字符串值:var relationshipName = GetRelationshipSchemaName<SalesOrder>(nameof(SalesOrder.SalesOrder_Annotation))
将此代码添加到应用程序中的帮助器类:
public static string GetRelationshipSchemaName<T>(string relationshipPropertyName) where T:Entity
{
return typeof (T).GetProperties()
.FirstOrDefault(x => x.Name == relationshipPropertyName)
.GetCustomAttributes()
.OfType<RelationshipSchemaNameAttribute>()
.FirstOrDefault()
?.SchemaName;
}
public static Relationship GetRelationship<T>(string relationshipPropertyName) where T : Entity
{
return new Relationship(typeof(T).GetProperties()
.FirstOrDefault(x => x.Name == relationshipPropertyName)
.GetCustomAttributes()
.OfType<RelationshipSchemaNameAttribute>()
.FirstOrDefault()
?.SchemaName);
}
这是您更新后的代码的样子:
var associateRequest = new AssociateRequest
{
Target =
new EntityReference(
SalesOrder.EntityLogicalName,
salesOrderGuid),
RelatedEntities =
new EntityReferenceCollection
{
new EntityReference(
Annotation
.EntityLogicalName,
noteGuid)
},
Relationship = GetRelationship<SalesOrder>(nameof(SalesOrder.SalesOrder_Annotation)) ///////////????
};