介绍
在日常开发中,我们常通过界面操作对实体进行新建,但是官方是提供了API供开发者通过代码直接创建实体,接下来我将简单介绍如何通过代码进行dynamics crm系统新实体新建。
环境准备
IDE : Visual Studio 2022
Package: Microsoft.CrmSdk.XrmTooling.CoreAssembly
实现代码
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Tooling.Connector;
using System;
namespace CreateEntity
{
internal class Program
{
static void Main(string[] args)
{
string CRMConnString = "AuthType=AD;Domain=;Username=;Url=;Password=;";
CrmServiceClient service = new CrmServiceClient(CRMConnString);
string prefix = "new"; //前缀
int languagecode = 2052; //简体中文
string tableSchemaName = $"{prefix}_Ribbon";
string primaryNameColumnName = $"{prefix}_Name";
string solutionUniqueName = "";//解决方案,按实际填写
CreateEntityRequest request = new CreateEntityRequest()
{
//Define the table
Entity = new EntityMetadata
{
SchemaName = tableSchemaName,// 架构名称
DisplayName = new Label("自定义按钮", languagecode),//显示名称
DisplayCollectionName = new Label("自定义按钮", languagecode), //显示集合名称:包含实体的复数显示名称的标签。
Description = new Label("自定义按钮", languagecode),//描述
OwnershipType = OwnershipTypes.UserOwned,//所有权类型
IsActivity = false,//实体是否为 activity。
IsMailMergeEnabled = new BooleanManagedProperty(true),//是否为此实体启用邮件合并。
},
// Define the primary name column for the table
PrimaryAttribute = new StringAttributeMetadata
{
SchemaName = primaryNameColumnName,// 架构名称
RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),//必需级别
MaxLength = 100,//最大长度
FormatName = StringFormatName.Text,//格式名称
DisplayName = new Label("名称", languagecode),//显示名称
Description = new Label("名称", languagecode) //描述
},
SolutionUniqueName = solutionUniqueName //获取或设置要向其添加此表的非托管解决方案的名称。可选
};
var response = (CreateEntityResponse)service.Execute(request);
Console.WriteLine($"Table ID:{response.EntityId}");
Console.WriteLine($"Primary name column ID:{response.AttributeId}");
}
}
}