Create a Custom Entity in Microsoft Dynamics CRM using SDK

In Microsoft Dynamics CRM 4.0, I need to create a custom entity using CRM SDK here are the code for that.

NOTE: for that you need to use Metadata Service

// Create an authentication token.
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.OrganizationName = "AdventureWorksCycle";

// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;

// Create the metadata Web service.
MetadataService metadataService = new MetadataService();
metadataService.Url = "http://:/MSCRMServices/2007/MetadataService.asmx";
metadataService.CrmAuthenticationTokenValue = token;
metadataService.Credentials = System.Net.CredentialCache.DefaultCredentials;
metadataService.PreAuthenticate = true;

// Create the entity.
EntityMetadata timesheetEntity = new EntityMetadata();
timesheetEntity.SchemaName = "new_timesheet";
timesheetEntity.OwnershipType = new CrmOwnershipTypes();
timesheetEntity.OwnershipType.Value = OwnershipTypes.UserOwned;
timesheetEntity.DisplayName = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.CreateSingleLabel("Timesheet", 1033);
timesheetEntity.DisplayCollectionName = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.CreateSingleLabel("Timesheets", 1033);
timesheetEntity.Description = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.CreateSingleLabel("Employee Timesheet", 1033);

// Create the primary attribute.
StringAttributeMetadata primaryAttribute = new StringAttributeMetadata();
primaryAttribute.SchemaName = "new_name";
primaryAttribute.RequiredLevel = new CrmAttributeRequiredLevel();
primaryAttribute.RequiredLevel.Value = AttributeRequiredLevel.None;
primaryAttribute.MaxLength = new MetadataServiceSdk.CrmNumber();
primaryAttribute.MaxLength.Value = 100;
primaryAttribute.DisplayName = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.CreateSingleLabel("Name", 1033);
primaryAttribute.Description = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.CreateSingleLabel("Employee Name", 1033);

// Create the entity request.
CreateEntityRequest createEntity = new CreateEntityRequest();
createEntity.Entity = timesheetEntity;
createEntity.HasActivities = false;
createEntity.HasNotes = true;
createEntity.PrimaryAttribute = primaryAttribute;

// Execute the request.
CreateEntityResponse entityResponse = (CreateEntityResponse )metadataService.Execute(createEntity);

// Publish the new custom entity.
// Note that the custom entities cannot be used until they have been published.
PublishAllXmlRequest publishAllRequest = new PublishAllXmlRequest();
PublishAllXmlResponse publishAllResponse = (PublishAllXmlResponse)metadataService.Execute(publishAllRequest);

One thought on “Create a Custom Entity in Microsoft Dynamics CRM using SDK

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.