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.

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.

To activate a 30-day trial, use the license key assigned to you after completing the registration on the Devart website.

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.

License details and the activation key

To activate a connection in your application, add the License Key to your connection string.

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.

Note
Make sure to replace your_username, your_password, and your_dynamics_url with your actual Dynamics 365 credentials and URL.
// 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.

View the table data in the console app

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.

Add a new connection

It opens the Change Data Source dialog. Select dotConnect for Dynamics 365 from the list of installed data providers.

Choose the data source as Dynamics 365

Fill in the necessary connection properties and click Test Connection to verify the settings. You can connect to Dynamics 365.

Provide Dynamics 365 connection details

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.

View the table data in the application

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 you don't have it already installed, close your Visual Studio instance, download Entity Developer, and install it following the on-screen instructions.

After that, follow the detailed illustrated guide to create your database model using Entity Developer. When this process is complete, the model you created opens for you to view it and start working with it.

View the ready EF Core model

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.

dotConnect for Dynamics 365

Get an enhanced ORM-enabled data provider for Dynamics 365 and develop .NET applications working with Dynamics 365 data quickly and easily!

Try the 30-day trial of the full product. No limits. No card required Start free trial