仅使用Microsoft.Xrm.Sdk.Entity
类 for CreateRequest
。下面的示例代码将使您了解如何在 CRM 2011 中创建一个简单的 CreateRequest
internal Guid CreateEntity(IServiceProvider serviceProvider)
{
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService organizationService = serviceFactory.CreateOrganizationService(null);
CreateRequest createRequest = new CreateRequest();
Entity entityToCreate = new Entity("Some_Entity_LogicalName");
createRequest.Target = entityToCreate;
CreateResponse response = (CreateResponse)organizationService.Execute(createRequest);
return response.id;
}
但是,如果我想为插件中的某个实体创建新记录 - 我使用以下较短的代码:
internal Guid CreateEntity(IServiceProvider serviceProvider)
{
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService organizationService = serviceFactory.CreateOrganizationService(null);
Entity entityToCreate = new Entity("Some_Entity_LogicalName");
return organizationService.Create(entityToCreate);
}
请注意,这只是一个示例代码,您不需要在每次保存/更新/删除某些实体时创建 OrganizationService。您可以为您的插件创建一次组织服务,将其存储在一些“全局”变量中,而不仅仅是在任何地方使用它