Save Big on Cyber Monday! Up to 40% Off
ends in   {{days}}
Days
{{timeFormat.hours}}
:
{{timeFormat.minutes}}
:
{{timeFormat.seconds}}

Connect C# to CRM Dynamics 365 With Entity Framework Core

Dynamics 365 is a powerful CRM and ERP solution from Microsoft, widely used for business applications. Integrating it with your .NET applications using Entity Framework Core (EF Core) allows developers to work with Dynamics 365 data using familiar ORM paradigms and LINQ queries.

In this tutorial, you will learn how to set up a connection between a C# application and Dynamics 365 using dotConnect for Dynamics 365 along with Entity Developer to generate EF Core models. This enables smooth and efficient data access in your .NET applications.

Why dotConnect for Dynamics 365?

  • Fully managed ADO.NET provider designed specifically for Dynamics 365 with optimized performance.
  • Support for EF Core with full LINQ and asynchronous programming support.
  • Seamless integration with Entity Developer for powerful ORM model design and code generation.
  • Simplified Dynamics 365 entity relationships with automatic mapping.
  • Rapid development without dealing directly with Dynamics 365 Web API complexities.

Prerequisites

What you will need for this tutorial:

  • Visual Studio 2022: Our IDE of choice. If you do not have it on your machine, go to the official website to download and install it. We will be using the community version; we recommend that you install it to follow the tutorial.
  • dotConnect for Dynamics 365: A feature-rich ADO.NET provider with EF Core and LINQ support.
  • Entity Developer: An ORM designer for .NET ORM Frameworks with powerful code generation for EF Core.
  • Dynamics 365 instance: You should have an active Dynamics 365 environment with proper credentials (username, password, and tenant ID) and application registration (Client ID and Client Secret) for OAuth authentication.

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.

License details and the activation key

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

Create a project

  1. Open Visual Studio and create a new Console App (.NET Core) project.
  2. Name your project DynamicsEFCore.
  3. Right-click your project in the Solution Explorer and select Manage NuGet Packages.
  4. Search for and install the following packages:

Check Dynamics 365 objects

To connect to Dynamics 365 using the built-in Data Explorer, right-click Data Connections and choose Add Connection.

Add Dynamics 365 Connection

Select Dynamics 365 as the data source, choose Web Login to get credentials, and click Test Connection.

Test Dynamics 365 Connection

If the test connection is successful, click OK.

Once connected, you can browse tables, execute queries, and manage data directly within Data Explorer.

View Dynamics 365 Role Data

Build Dynamics 365 EF Core model

The Professional and Developer editions of dotConnect for Dynamics 365 come equipped with Entity Developer - a robust ORM model designer and code generator that supports both Entity Framework and EF Core. This tool simplifies the process of generating a model from a data source or creating a data source from an existing model.

1. Add Devart EF Core Model to the project. To do this, right-click the project node in Solution Explorer, select Add, and click New Item.

Add EF Core Model

In the Add New Item dialog, select the Data category, choose the Devart EF Core Model template, and click Add. This automatically launches Entity Developer's Create New Model wizard that creates a new empty model or generates it from the data source.

Select EF Core Model

3. Choose Database First approach and click Next on the welcome screen.

Create Model Wizard

4. Configure the Dynamics 365 connection:

Enter your Dynamics 365 domain.

Click Web Login to obtain a Refresh Token, similar to the one in the Data Explorer connection.

Dynamics 365 Connection Settings

Click Next.

5. Choose the Dynamics 365 objects for your model. In this example, we will use role-related tables. Click Next.

Select Database Objects

6. Set up property naming conventions for data source objects. We recommend using the default settings for this tutorial. Click Next.

Naming Settings

7. Configure the necessary settings for the model. In particular, select the file to save the connection, specify connection string versions, and define the names of DbContext classes. Then, click Next.

Model Properties Settings

8. Choose the model diagram content. You can use all entities, split the entities by database, or customize the selection. For this tutorial, select All Entities, then click Next.

Choose Model Diagram Contents

9. Choose code generation templates for your objects. You can define parameters according to your preferences or apply default settings. For this tutorial, use the default settings. Click Next.

Code Generation Settings

Your model is ready now.

Click Finish.

Finish Wizard

The created model opens.

Model Diagram

The model you just created is now ready for use.

Entity Developer generates classes for the selected tables, representing data entities. It also creates a Model class descendant, which manages the connection to the Dynamics 365 CRM database and handles data flow. This class contains properties and methods corresponding to your Dynamics 365 CRM objects, allowing you to retrieve and modify data easily.

The generated code can be found in:

  • DataModel1.Contact.cs - Contains entity definitions.
  • DataModel1.Model.cs - Custom partial classes and methods that you can add here to extend the functionality.

With the model set up, you are now ready to interact with Dynamics 365 data using Entity Framework Core in your .NET application.

Note
If you're using a purchased dotConnect for Dynamics 365 license, include the license key in the connection strings. In our case, we will keep it in the DbContext class:
optionsBuilder.UseDynamics(@"User ID=*******; Password=*******; Server=*******; License Key=*******");

Read data from Dynamics 365

In the Program.cs file, write the code to retrieve and display information from the Contacts table.

using System;
using System.Linq;

namespace DynamicsEFCore
{
  class Program
  {
    static void Main(string[] args)
    {
      using (var context = new Model())
      {
        var contacts = context.Contacts
          .Take(10)
          .ToList();

        foreach (var contact in contacts)
        {
          Console.WriteLine($"Name: {contact.Firstname} {contact.Lastname}, Phone: {contact.Mobilephone}");
        }
      }
    }
  }
}

The console should display the First name, Last name, and Phone fields from the Contacts table in Dynamics 365.

Insert new data into Dynamics 365

To insert a new row into the Contact table in Dynamics 365 using EF Core, follow these steps:

Step 1: Prepare your data

Ensure you have the necessary data for the new Contact you want to insert. For this example, we'll use the following data:

  • First name: TestName
  • Last name: TestLastName
  • Phone: +12345678910
  • OwnerId: ********** (important field)

Step 2: Write the code to insert a new role

In your Program.cs file, add the following code to insert a new row into the Contact table:

using System;
using System.Linq;

namespace DynamicsEFCore
{
  class Program
  {
    static void Main(string[] args)
    {
      using (var context = new Model())
      {
        // Create a new Contact object
        var newContact = new Contact
        {
          Firstname = "TestName",
          Lastname = "TestLastName",
          Mobilephone = "+12345678910",
          Ownerid = Guid.Parse("**********")
        };

        // Add the new Contact to the context
        context.Contacts.Add(newContact);

        // Save changes to the database
        context.SaveChanges();

        // Retrieve and display the added contact
        var addedContact = context.Contacts
          .OrderByDescending(c => c.Createdon)
          .FirstOrDefault();

        if (addedContact != null)
        {
          Console.WriteLine("Added Contact:");
          Console.WriteLine($"First Name: {addedContact.Firstname}");
          Console.WriteLine($"Last Name: {addedContact.Lastname}");
          Console.WriteLine($"Mobile Phone: {addedContact.Mobilephone}");
          Console.WriteLine($"Created On: {addedContact.Createdon}");
        }
        else
        {
          Console.WriteLine("Failed to add the contact.");
        }
      }
    }
  }
}

Build and run your application.

Console Output

Update Dynamics 365 data

Now, let's update the phone number for an account with the name "John Doe" in Dynamics 365. This example assumes that the full name is unique or that you have a way to uniquely identify the account you want to update.

We retrieve the account named "John Doe" from the database and update the Mobilephone property with the new phone number.

Here's how you can implement this in your Program class:

using System;
using System.Linq;

namespace DynamicsEFCore
{
  class Program
  {
    static void Main(string[] args)
    {
      using (var context = new Model())
      {
        // Find the contact with Firstname "John" and Lastname "Doe"
        var contact = context.Contacts
          .FirstOrDefault(c => c.Firstname == "John" && c.Lastname == "Doe");

        if (contact != null)
        {
          // Update the mobile phone with a random value
          var random = new Random();
          contact.Mobilephone = $"+1{random.Next(1000000000, 1999999999)}";

          context.SaveChanges();
          Console.WriteLine($"Updated mobile phone for John Doe: {contact.Mobilephone}");
        }
        else
        {
          Console.WriteLine("Contact John Doe not found.");
        }
      }
    }
  }
}

When this code is executed successfully, the mobile phone for the selected account is updated.

Console Output Update

Delete data from Dynamics 365

This example demonstrates how to fetch the account by name and then delete it from the database.

First, retrieve the contact with the name "TestName TestLastName" from the database.

Once you have retrieved the account, remove it from the DbContext and save the changes.

Here's how you can implement this in your Program class:

using System;
using System.Linq;

namespace DynamicsEFCore
{
  class Program
  {
    static void Main(string[] args)
    {
      using (var context = new Model())
      {
        var contact = context.Contacts
            .FirstOrDefault(c => c.Firstname == "TestName" && c.Lastname == "TestLastName");

        if (contact != null)
        {
          context.Contacts.Remove(contact);
          context.SaveChanges();
          Console.WriteLine("Contact TestName TestLastName deleted.");
        }
        else
        {
          Console.WriteLine("Contact TestName TestLastName not found.");
        }
      }
    }
  }
}

As a result, the selected contact is deleted from the database.

Console Output Delete

Conclusion

Using dotConnect for Dynamics 365 with Entity Framework Core and Entity Developer offers a robust, efficient, and developer-friendly way to work with Dynamics 365 data in C#. This approach abstracts the complexities of the Dynamics 365 API, providing seamless integration and full ORM benefits.

With the provided steps, you can quickly set up your project, generate EF Core models, and perform CRUD operations on Dynamics 365 entities, accelerating your application development.

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!

Discover the ultimate capabilities of dotConnect for Dynamics 365 Download free trial