How to connect to Dynamics 365 in .NET with C#
Dynamics 365 is an AI-powered platform from Microsoft that provides a comprehensive suite of services for managing sales, customer service, finance, marketing, and operations. This unified solution consolidates data, automates repetitive business processes, and improves customer engagement. Its ERP and CRM applications integrate smoothly with existing systems and serve as a central data source for various business applications.
When developing applications based on Dynamics 365, connectivity plays a crucial role. Applications must be able to connect to the data source easily and reliably, retrieve the necessary data, and perform data operations directly within the system. This need is effectively addressed by dotConnect for Dynamics 365, a robust data provider that enables direct connections and supports all necessary data operations.
This article explores different methods of connecting to Dynamics 365 from .NET applications.
Why choose dotConnect for Dynamics 365?
dotConnect for Dynamics 365 is an ideal data provider designed for all data operations in Dynamics 365. The simple connector creation, flexible configuration, absolute integration with Visual Studio, and advanced ORM support allow this dotConnect provider to improve the application functionality and performance, also simplifying the daily work of .NET developers working with Dynamics 365 data.
Requirements
- Visual Studio 2022: Our IDE of choice. If you do not have this IDE on your machine, visit the official website and install it. We will use the free Community Edition.
- dotConnect for Dynamics 365: A robust ADO.NET provider for Dynamics 365 with Entity Framework, NHibernate, and LinqConnect support.
- Entity Developer: An ORM designer for .NET ORM Frameworks with powerful code generation capabilities.
Download and activate dotConnect for Dynamics 365
30-day free trial version
Download and install dotConnect for Dynamics 365 directly on your machine, or install the Devart.Data.Dynamics NuGet package.
No license key is required, and you can start exploring the product immediately.
Full version
After purchasing the full version, go to your profile's Licenses page. Choose your product and click Details. Here, you'll find the license details and the Activation Key.
To activate a connection in your application, add the License Key to your connection string.
Create a .NET project
We start with creating a new C# Project. Open Visual Studio, click Create a new project and choose Console App (.NET Core/.NET Framework).
Then give this project a name (ours is DynamicsConsoleApp; we'll use this name through this tutorial). Click Create.
Next, install dotConnect for Dynamics 365 via the NuGet Package Manager in Visual Studio. On the taskbar, click Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
Search for Devart.Data.Dynamics NuGet Package and install it for your project.
Connect using C#
We have created a console application. The code below ensures connection to Dynamics 365 and retrieves the first rows from the role table.
// Define your connection string string connectionString = "User [email protected];Password=*******;Server=dynamics.com;License Key=*******"; // Create a connection to Dynamics 365 using (DynamicsConnection connection = new DynamicsConnection(connectionString)) { try { // Open the connection connection.Open(); Console.WriteLine("Connection successful!"); // Create a command to retrieve data from the 'role' table DynamicsCommand command = new DynamicsCommand("SELECT roleid, name, createdon FROM role", connection); // Execute the command and retrieve the data using (DynamicsDataReader reader = command.ExecuteReader()) { int rowCount = 0; const int maxRows = 8; // Display the results while (reader.Read() && rowCount < maxRows) { Console.WriteLine($"Role ID: {reader["roleid"]},\nName: {reader["name"]},\nCreated On: {reader["createdon"]}\n"); rowCount++; } } } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } }
After establishing the connection, the app retrieves the first eight rows from the role table and displays them in the console.
Connect using Server Explorer
You can connect to your Dynamics 365 data using the Server Explorer. Right-click Data Connections and select Add Connection from the context menu.
It opens the Change Data Source dialog. Select dotConnect for Dynamics 365 from the list of installed data providers.
Fill in the necessary connection properties and click Test Connection to verify the settings. You can connect to Dynamics 365.
After connecting, expand the newly-created data connection in the Server Explorer and view the data source structure, including all tables and table columns. To view the data from some particular table, right-click it and select Retrieve Data from Table. This action opens a new query window with a SELECT statement to fetch the data from the table.
Connect with EF Core using Entity Developer
Entity Developer is a powerful visual ORM builder that enables developers to create EF Core models from Dynamics 365. If this is your use case, let's explore how to connect to Dynamics 365 using EF Core and Entity Developer.
Right-click the solution and navigate to Add > New Item.
Select Data and click Devart EF Core Model.
The Entity Developer Model wizard opens. Select Database First and click Next.
Enter your connection details for Dynamics 365. Click Test Connection to verify the credentials, and click Next to proceed.
In the Choose Model Contents, select Generate From Database and click Next.
In the Select database objects window, define the objects to scaffold.
Define the naming convention for the database object property names to follow. In this tutorial, we keep the default settings. Click Next.
Set up the model properties, such as the namespace and entity container.
Choose the contents of the Model Diagram. You can use all entities, split them by database, or do a custom selection for your specific scenario. We choose to include all entities in the diagram.
Finally, choose the code generation templates for the model. You can define different parameters to follow.
The model is complete. You can download Devart.Data.Dynamics.EFCore if needed. Click Finish.
You can view the generated model and start working with it.
Connect with EF Core using Scaffold-DbContext
Another method of connecting to Dynamics 365 involves using Entity Framework Core (EF Core) and the Scaffold-DbContext command. Here, we will generate the necessary EF Core model classes and DbContext based on the existing database schema.
First of all, we need to install the required NuGet packages via the Solution Explorer in Visual Studio and the Manage NuGet Packages options:
Open the Package Manager Console: Tools > NuGet Package Manager > Package Manager Console.
Run the following command to scaffold the DbContext and entity classes from your data source. Ensure to replace the connection string with your actual connection details.
Scaffold-DbContext "Server=test.crm4.dynamics.com;[email protected];Password=******;License Key=******;" Devart.Data.Dynamics.Entity.EFCore -OutputDir Models
Notice that the -OutputDir Models parameter specifies the output directory to store the generated model classes (in this case, it is Models). After running the scaffold command, EF Core will generate the DbContext class and entity classes in the specified output directory.
Review the generated code and check how it matches your database schema.
Conclusion
Dynamics 365 is a popular platform for data-driven business applications, and integrating it into your work environment is a common task for many organizations where ensuring stable connectivity between the database and the application is crucial. dotConnect for Dynamics 365 effectively resolves all challenges, allowing developers to connect directly to the data source and utilize it in their applications.
You can explore dotConnect for Dynamics 365 with a fully functional 30-day free trial. Experience its benefits firsthand and see how it can improve your daily workflows.