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.

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.

To activate your 30-day trial, use the license key you receive after registering 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.

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.

Follow the detailed illustrated guide to create your database model using Entity Developer. When this process is complete, the model you created opens, ready for use.

Model diagram

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:

Microsoft.EntityFrameworkCore.Design

Microsoft.Extensions.Configuration.FileExtensions

Microsoft.Extensions.Configuration.Json

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!

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