Connect C# to SugarCRM With Entity Framework Core

SugarCRM is a flexible and feature-rich customer relationship management platform used by businesses to manage contacts, sales, and workflows. In this tutorial, you'll learn how to integrate SugarCRM into a C# application using Entity Framework Core and dotConnect for SugarCRM, enabling you to work with CRM data through a strongly-typed, object-oriented model.

Why dotConnect for SugarCRM?

dotConnect for SugarCRM streamlines .NET development by eliminating the complexity of native SugarCRM APIs and providing secure, high-performance access to CRM data through familiar ADO.NET interfaces. Designed for scalability and developer productivity, it offers advanced ORM support and broad platform compatibility.

  • No client libraries required: Connect to SugarCRM directly without installing or managing external dependencies.
  • Standard ADO.NET interface: Query SugarCRM data using well-known ADO.NET classes for a fast, familiar development experience.
  • Advanced ORM integration: Benefit from rapid model-based access enabled through the support of Entity Framework Core, Dapper, NHibernate, and other primary ORM tools.
  • Full SugarCRM API support: Take advantage of the compatibility with all current versions of the SugarCRM API and built-in support of CRM-specific features.
  • Optimized query engine: Use SQL-92 syntax to query data, with simple queries executed remotely and complex ones processed via a built-in local SQL engine.
  • Visual Studio Integration: Leverage built-in wizards and tools to manage connections, schema mapping, and code generation directly from within Visual Studio.

With strong security practices, regular updates, and dedicated support, dotConnect for SugarCRM is the trusted choice for embedding CRM data into .NET applications—from dashboards to analytics and business process automation.

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 edition; we recommend that you install it to follow the tutorial.
  • dotConnect for SugarCRM: A feature-rich ADO.NET provider with support for Entity Framework, NHibernate, and EF Core. For installation instructions, refer to the next section.
  • Entity Developer: An ORM designer for .NET ORM frameworks with powerful code generation. For now, just download the installer.

Download and activate dotConnect for SugarCRM

30-day free trial version

Download and install dotConnect for SugarCRM directly on your computer or install the Devart.Data.Sugar NuGet package.

No license key is required; 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 .NET Core project

  1. Open Visual Studio, select Create a new project > Console App (.NET Core), and click Next.
  2. Name your project; for this tutorial, let's name the project SugarEFCore. Specify the project's location and click Next.
  3. To create the project, click Create.
  4. In Solution Explorer, right-click the project you created and select Manage NuGet Packages.
  5. Navigate to the Browse tab, search for the Devart.Data.Sugar.EFCore package, and install it.

Check SugarCRM objects

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

Add SugarCRM Connection

Then, select the SugarCRM data source, enter your SugarCRM domain, and click Web Login. Click Test Connection to verify connectivity.

Test SugarCRM 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 SugarCRM Data

Build SugarCRM EF Core model

Let's start by generating an EF Core model from your SugarCRM instance using Entity Developer. This way, you can map CRM entity 'Contacts' directly to C# classes.

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

2. 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 the Database First approach and click Next on the welcome screen.

Create Model wizard

4. Configure the SugarCRM connection. Enter your SugarCRM connection properties, similar to the ones in the Data Explorer connection.

EF Core connection settings

Click Next and choose model contents.

Choose model contents

5. Choose the SugarCRM objects for your model. In this example, we will use the Contacts table. 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 model you have created opens.

Model diagram

The model you just created is now ready for use.

Once the model is created, Entity Developer generates clean, structured C# code representing your SugarCRM schema. Let's take a quick look at what is created and how it fits into your project.

The generated code can be found in:

  • DataModel1.Contact.cs - Entity definitions.
  • DataModel1.sugarModel.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 SugarCRM data using Entity Framework Core in your .NET application.

Note

If you're using a purchased dotConnect for SugarCRM license, include the license key in the connection strings.

In our case, we will keep our connection strings in appsettings.json:

{
  "ConnectionStrings": {
    "sugarModelConnectionString": "User Id=TestUser;Password=TestPassword;Host=https://test.sugaropencloud.eu;License key=**********"
  }
}

For working with JSON, we also need the following NuGet packages:

Read data from SugarCRM

With your model in place, you can now query SugarCRM. This section shows how to retrieve and filter CRM records using LINQ and EF Core's familiar syntax.

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using SugarEFCore;

// Build configuration
var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

// Get connection string
var connectionString = configuration.GetConnectionString("sugarModelConnectionString");

// Configure DbContext
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSugar(connectionString);

// Create DbContext instance
using (var db = new sugarModel(optionsBuilder.Options))
{
    Console.WriteLine("Contacts Table:");

    // Print header
    Console.WriteLine("{0,-25} | {1,-15} | {2,-20} | {3,-30}", "Name", "Work Phone", "City", "Email");
    Console.WriteLine(new string('-', 90));

    // Query and display contacts
    var contacts = db.Contacts.Take(10).ToList();
    foreach (var contact in contacts)
    {
        var fullName = $"{contact.FirstName} {contact.LastName}";
        Console.WriteLine("{0,-25} | {1,-15} | {2,-20} | {3,-30}", 
            fullName, 
            contact.PhoneWork, 
            contact.PrimaryAddressCity, 
            contact.Email1);
    }
}

The console should display the Name, Work Phone, City, and Email fields from the Contacts table in SugarCRM.

Read SugarCRM data

Insert new data into SugarCRM

Need to create new CRM entries? The following example shows how to add a new contact directly into SugarCRM using EF Core:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using SugarEFCore;

// Build configuration
var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

// Get connection string
var connectionString = configuration.GetConnectionString("sugarModelConnectionString");

// Configure DbContext
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSugar(connectionString);

// Create DbContext instance
using (var db = new sugarModel(optionsBuilder.Options))
{
    // Create a new Contact entity using EF Core
    var newContact = new Contact
    {
        FirstName = "Testy",
        LastName = "McTesterson",
        PhoneWork = "555-123-4567",
        PrimaryAddressCity = "Testville"
    };

    // Add the entity to the DbContext and save changes
    db.Contacts.Add(newContact);
    db.SaveChanges();
    Console.WriteLine("Contact inserted successfully.");
    Console.WriteLine();

    // Query for the newly inserted contact by finding the most recent one
    var insertedContact = db.Contacts.OrderByDescending(c => c.DateEntered).FirstOrDefault();

    if (insertedContact != null)
    {
        Console.WriteLine("Newly Inserted Row:");
        // Print header
        Console.WriteLine("{0,-25} | {1,-15} | {2,-20}", "Name", "Work Phone", "City");
        Console.WriteLine(new string('-', 75));

        // Print contact details
        var fullName = $"{insertedContact.FirstName} {insertedContact.LastName}";
        Console.WriteLine("{0,-25} | {1,-15} | {2,-20}",
            fullName,
            insertedContact.PhoneWork,
            insertedContact.PrimaryAddressCity);
    }
    else
    {
        Console.WriteLine("Could not find the newly inserted contact.");
    }
}

Build and run your application.

Insert data into SugarCRM

Update SugarCRM data

CRM data is always evolving. This section demonstrates how to load existing SugarCRM records, apply changes, and persist updates with EF Core:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using SugarEFCore;

// Build configuration
var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

// Get connection string
var connectionString = configuration.GetConnectionString("sugarModelConnectionString");

// Configure DbContext
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSugar(connectionString);

// Create DbContext instance
using (var db = new sugarModel(optionsBuilder.Options))
{
    // Find the contact to update
    Console.WriteLine("Finding contact to update...");
    var contactToUpdate = db.Contacts
        .Where(c => c.FirstName == "Testy" && c.LastName == "McTesterson")
        .OrderByDescending(c => c.DateEntered)
        .FirstOrDefault();

    if (contactToUpdate != null)
    {
        Console.WriteLine($"Found contact with ID: {contactToUpdate.Id}.");

        // Update the first and last name
        contactToUpdate.FirstName = "Final";
        contactToUpdate.LastName = "Test";

        db.SaveChanges();
        Console.WriteLine("Contact updated successfully.");
        Console.WriteLine();

        Console.WriteLine("Updated Row:");
        // Print header
        Console.WriteLine("{0,-25} | {1,-15} | {2,-20}", "Name", "Work Phone", "City");
        Console.WriteLine(new string('-', 75));

        // Print contact details
        var fullName = $"{contactToUpdate.FirstName} {contactToUpdate.LastName}";
        Console.WriteLine("{0,-25} | {1,-15} | {2,-20}",
            fullName,
            contactToUpdate.PhoneWork,
            contactToUpdate.PrimaryAddressCity);
    }
    else
    {
        Console.WriteLine("Could not find the contact 'Testy McTesterson' to update.");
    }
}

Below is the result of this code execution.

Update SugarCRM data

Delete data from SugarCRM

When records are no longer needed, you can remove them cleanly. Here, we show how to delete CRM data while keeping your application's logic clear and safe:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using SugarEFCore;

// Build configuration
var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

// Get connection string
var connectionString = configuration.GetConnectionString("sugarModelConnectionString");

// Configure DbContext
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSugar(connectionString);

// Create DbContext instance
using (var db = new sugarModel(optionsBuilder.Options))
{
    // Find the contact to delete
    Console.WriteLine("Finding contact to delete...");
    var contactToDelete = db.Contacts
        .Where(c => c.FirstName == "Final" && c.LastName == "Test")
        .OrderByDescending(c => c.DateEntered)
        .FirstOrDefault();

    if (contactToDelete != null)
    {
        Console.WriteLine($"Found contact with ID: {contactToDelete.Id}.");

        // Delete the contact using EF Core
        db.Contacts.Remove(contactToDelete);
        db.SaveChanges();
        Console.WriteLine("Contact deleted successfully.");
        Console.WriteLine();

        // Verify the contact has been deleted
        Console.WriteLine("Verifying deletion...");
        var deletedContact = db.Contacts.Find(contactToDelete.Id);

        if (deletedContact == null)
        {
            Console.WriteLine("Verification successful. The contact has been removed.");
        }
        else
        {
            Console.WriteLine("Verification failed. The contact still exists.");
        }
    }
    else
    {
        Console.WriteLine("Could not find the contact 'Final Test' to delete.");
    }
}

As a result, data is deleted from the database.

Delete data from SugarCRM

Conclusion

By connecting C# to SugarCRM with EF Core, you've built a powerful and maintainable data access layer. Using Entity Developer streamlines the entire process, from model creation to CRUD operations, giving you full control over CRM data in your .NET applications.

dotConnect for SugarCRM

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

Discover the ultimate capabilities of dotConnect for SugarCRM Download free trial