在crm2011里面,创建lookup类型的字段不能直接创建,需要通过创建关系来创建,下面给出一个事例:
using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Crm.Sdk.Messages;
/// <summary>
/// 创建Lookup字段
/// </summary>
public class CreateOneToManyHelper
{
public void Create(IOrganizationService service)
{
//构造Request对象
CreateOneToManyRequest oneRequest = new CreateOneToManyRequest();
//Lookup对象
LookupAttributeMetadata lookup = new LookupAttributeMetadata();
//字段名称
lookup.LogicalName = "new_company";
//架构名称
lookup.SchemaName = "new_company";
//显示中文名称
lookup.DisplayName = new Label("公司", 2052);
//描述
lookup.Description = new Label("Lookup字段", 2052);
//需求级别
lookup.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);
//字段安全性
lookup.IsSecured = false;
//审核
lookup.IsAuditEnabled = new BooleanManagedProperty(false);
oneRequest.Lookup = lookup;
//关系
OneToManyRelationshipMetadata shipMetadata = new OneToManyRelationshipMetadata();
//关联实体
shipMetadata.ReferencedEntity = "new_company";
//关联实体的属性
shipMetadata.ReferencedAttribute = "new_companyid";
//主要实体
shipMetadata.ReferencingEntity = "new_class";
//关系名称
shipMetadata.SchemaName = "new_class_new_company";
shipMetadata.AssociatedMenuConfiguration = new AssociatedMenuConfiguration() {
//显示选项
Behavior = AssociatedMenuBehavior.UseLabel,
//显示区域
Group = AssociatedMenuGroup.Service,
//自定义标签
Label = new Label("关联公司",2052),
//显示顺序
Order = 10001
};
//关系行为
shipMetadata.CascadeConfiguration = new CascadeConfiguration() {
//分配,无级联
Assign = CascadeType.NoCascade,
//删除,移除链接
Delete = CascadeType.RemoveLink,
//合并,无级联
Merge = CascadeType.NoCascade,
//重定父,无级联
Reparent = CascadeType.NoCascade,
//共享,无级联
Share = CascadeType.NoCascade,
//取消共享,无级联
Unshare = CascadeType.NoCascade
};
oneRequest.OneToManyRelationship = shipMetadata;
CreateOneToManyResponse response = (CreateOneToManyResponse)service.Execute(oneRequest);
System.Console.WriteLine("创建关系成功!");
service.Execute(new PublishAllXmlRequest());
System.Console.WriteLine("发布成功!");
}
}