Connect C# to SugarCRM With Dapper

SugarCRM offers a powerful way to manage customer data, and with dotConnect for SugarCRM, you can work with that data using familiar SQL. In this tutorial, you'll learn how to connect to SugarCRM and perform fast, low-overhead data operations in C# using Dapper, a lightweight micro-ORM that works directly with SQL commands.

Why dotConnect for SugarCRM?

dotConnect for SugarCRM streamlines .NET development by eliminating the complexity of native SugarCRM APIs and enabling 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 and familiar development experience.
  • Advanced ORM integration: Supports Entity Framework Core, Dapper, NHibernate, and other major ORM tools for rapid model-based access.
  • Full SugarCRM API support: Compatible with all current versions of the SugarCRM API and designed to support CRM-specific features.
  • Optimized query engine: Use SQL-92 syntax to query data; simple queries execute remotely, while complex ones are processed by a built-in local SQL engine.
  • Visual Studio integration: Leverage built-in wizards and tools to manage connections, schema mapping, and code generation directly within Visual Studio.

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

Prerequisites

Before you begin, make sure you have the following prerequisites in place:

  • Visual Studio 2026: This is the IDE of choice for .NET development. If you don't have it installed, you can download the free Community Edition from the official Microsoft website.
  • dotConnect for SugarCRM: A high-performance ADO.NET data provider for SugarCRM with enhanced ORM support and flawless database connectivity.
  • SugarCRM account: An active SugarCRM account with the necessary permissions for accessing and managing data.

Download and activate dotConnect for SugarCRM

30-day free trial version

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

No license key is required, so you can start exploring the product immediately.

Full version

After purchasing the full version, go to your profile's Product licenses page. Choose the 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 the connection string.

Create a .NET Core project

1. In Visual Studio, click Create a new project.

2. Select ConsoleApp (.NET Framework) and click Next.

3. Name the project, specify the path to its folder, and click Create. For this tutorial, we'll call it SugarDapper.

4. In the Solution Explorer, right-click the project and select Manage NuGet Packages.

5. Go to the Browse tab and search for and install the Devart.Data.Sugar and Dapper packages.

Check SugarCRM objects

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

Then, select SugarCRM Data Source.

Select the Add Connection option

Enter the required SugarCRM domain and click Test Connection.

Select the Test Connection option

If the test connection is successful, click OK.

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

Tables in the Data Explorer

Connect to SugarCRM and retrieve data

Let's start by establishing a SQL-based connection to SugarCRM using dotConnect. Then, we'll use Dapper to execute a query and retrieve records from the Contacts tables.

Create Contacts.cs (Model Class)

This class maps to the Contacts table:

namespace SugarDapper
{
    public class Contacts
    {
        public string? Name { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        public string? WorkPhone { get; set; }
        public string? City { get; set; }
        public string? Email { get; set; }
    }
}

Create DatabaseConnection.cs (Connection Strings)

This class keeps connection details separate for better maintainability.

namespace SugarDapper
{
    public class DatabaseConnection
    {
        public static string ConnectionString = "User Id=TestUser;Password=TestPassword;Host=https://test.sugaropencloud.eu;License key=***********";
    }
}

Add the following code to Program.cs.

using SugarDapper;
using System.Data;
using Devart.Data.Sugar;
using Dapper;

public class Program
{
    public static void Main(string[] args)
    {
        try
        {
            using (IDbConnection dbConnection = new SugarConnection(DatabaseConnection.ConnectionString))
            {
                dbConnection.Open();

                // Query to retrieve the top 10 contacts
                string query = "SELECT name AS Name, phone_work AS WorkPhone, primary_address_city AS City, email1 AS Email FROM Contacts LIMIT 10";

                // Execute the query and map the results to the Contacts model
                IEnumerable<Contacts> contacts = dbConnection.Query<Contacts>(query);

                // Display the contacts in a table format
                Console.WriteLine("{0,-30} {1,-20} {2,-20} {3,-30}", "Name", "Work Phone", "City", "Email");
                Console.WriteLine(new string('-', 100));

                foreach (var contact in contacts)
                {
                    Console.WriteLine("{0,-30} {1,-20} {2,-20} {3,-30}", contact.Name, contact.WorkPhone, contact.City, contact.Email);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

Build and run the application by pressing F5 or selecting Start from the menu.

Displayed connection details

Insert a new record using Dapper

This section shows how to use the INSERT SQL statement with Dapper to create a new record in SugarCRM — perfect for adding contacts through your .NET app.

using SugarDapper;
using System;
using System.Collections.Generic;
using System.Data;
using Devart.Data.Sugar;
using Dapper;

public class Program
{
    public static void Main(string[] args)
    {
        try
        {
            using (IDbConnection dbConnection = new SugarConnection(DatabaseConnection.ConnectionString))
            {
                dbConnection.Open();

                // Create a new contact object with test data
                var newContact = new Contacts
                {
                    FirstName = "Test",
                    LastName = "Contact",
                    WorkPhone = "123-456-7890",
                    City = "Test City",
                    Email = "[email protected]"
                };

                // SQL query to insert the new contact
                string insertQuery = @"
                    INSERT INTO Contacts (first_name, last_name, phone_work, primary_address_city, email1)
                    VALUES (@FirstName, @LastName, @WorkPhone, @City, @Email)";

                // Execute the insert query
                dbConnection.Execute(insertQuery, newContact);

                Console.WriteLine("Successfully inserted new contact.\n");

                // Query to retrieve the newly inserted contact
                string selectQuery = "SELECT name AS Name, phone_work AS WorkPhone, primary_address_city AS City, email1 AS Email FROM Contacts WHERE first_name = @FirstName AND last_name = @LastName";

                // Execute the query and get the new contact
                Contacts? insertedContact = dbConnection.QuerySingleOrDefault<Contacts>(selectQuery, new { newContact.FirstName, newContact.LastName });

                // Display the new contact in a table format
                Console.WriteLine("Newly Inserted Contact:\n");
                Console.WriteLine("{0,-30} {1,-20} {2,-20} {3,-30}", "Name", "Work Phone", "City", "Email");
                Console.WriteLine(new string('-', 100));

                if (insertedContact != null)
                {
                    Console.WriteLine("{0,-30} {1,-20} {2,-20} {3,-30}", insertedContact.Name, insertedContact.WorkPhone, insertedContact.City, insertedContact.Email);
                }
                else
                {
                    Console.WriteLine("Could not retrieve the newly inserted contact.");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

The result is as follows:

Add a new record

Update SugarCRM data using Dapper

Need to change existing data? Here, you'll learn how to run the UPDATE query with Dapper to modify records in SugarCRM based on conditions such as name.

using SugarDapper;
using System;
using System.Collections.Generic;
using System.Data;
using Devart.Data.Sugar;
using Dapper;

public class Program
{
    public static void Main(string[] args)
    {
        try
        {
            using (IDbConnection dbConnection = new SugarConnection(DatabaseConnection.ConnectionString))
            {
                dbConnection.Open();

                // Define the original and new names for the update
                var updateParams = new { 
                    OriginalFirstName = "Test", 
                    OriginalLastName = "Contact",
                    NewFirstName = "Updated Test", 
                    NewLastName = "Contact"
                };

                // SQL query to update the contact's first and last name
                string updateQuery = @"
                    UPDATE Contacts
                    SET first_name = @NewFirstName, last_name = @NewLastName
                    WHERE first_name = @OriginalFirstName AND last_name = @OriginalLastName";

                // Execute the update query
                int rowsAffected = dbConnection.Execute(updateQuery, updateParams);
                
                if (rowsAffected > 0)
                {
                    Console.WriteLine("Successfully updated contact.\n");
                }
                else
                {
                    Console.WriteLine("Could not find the contact to update.\n");
                }

                // Query to retrieve the updated contact
                string selectQuery = "SELECT name AS Name, phone_work AS WorkPhone, primary_address_city AS City, email1 AS Email FROM Contacts WHERE first_name = @NewFirstName AND last_name = @NewLastName";

                // Execute the query and get the updated contact
                Contacts? updatedContact = dbConnection.QuerySingleOrDefault<Contacts>(selectQuery, updateParams);

                // Display the updated contact in a table format
                Console.WriteLine("Updated Contact:\n");
                Console.WriteLine("{0,-30} {1,-20} {2,-20} {3,-30}", "Name", "Work Phone", "City", "Email");
                Console.WriteLine(new string('-', 100));

                if (updatedContact != null)
                {
                    Console.WriteLine("{0,-30} {1,-20} {2,-20} {3,-30}", updatedContact.Name, updatedContact.WorkPhone, updatedContact.City, updatedContact.Email);
                }
                else
                {
                    Console.WriteLine("Could not retrieve the updated contact.");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

Here's the output:

Result with the updated row

Delete SugarCRM data using Dapper

With Dapper, it's easy to remove outdated records. This section demonstrates how to execute the DELETE statement to clean up data from SugarCRM tables.

using SugarDapper;
using System;
using System.Collections.Generic;
using System.Data;
using Devart.Data.Sugar;
using Dapper;

public class Program
{
    public static void Main(string[] args)
    {
        try
        {
            using (IDbConnection dbConnection = new SugarConnection(DatabaseConnection.ConnectionString))
            {
                dbConnection.Open();

                // Define the contact to be deleted
                var deleteParams = new { 
                    FirstName = "Updated Test", 
                    LastName = "Contact" 
                };

                // SQL query to delete the contact
                string deleteQuery = @"
                    DELETE FROM Contacts
                    WHERE first_name = @FirstName AND last_name = @LastName";

                // Execute the delete query
                int rowsAffected = dbConnection.Execute(deleteQuery, deleteParams);
                
                if (rowsAffected > 0)
                {
                    Console.WriteLine($"Successfully deleted {rowsAffected} contact(s).\n");
                }
                else
                {
                    Console.WriteLine("Could not find the contact to delete.\n");
                }

                // Query to verify the deletion (try to retrieve the deleted contact)
                string selectQuery = "SELECT name AS Name, phone_work AS WorkPhone, primary_address_city AS City, email1 AS Email FROM Contacts WHERE first_name = @FirstName AND last_name = @LastName";

                // Execute the query and try to get the deleted contact
                Contacts? deletedContact = dbConnection.QuerySingleOrDefault<Contacts>(selectQuery, deleteParams);

                // Display the result of the deletion verification
                Console.WriteLine("Deletion Verification:\n");
                if (deletedContact == null)
                {
                    Console.WriteLine("Contact 'Updated Test Contact' was successfully removed from the database.");
                }
                else
                {
                    Console.WriteLine("Contact 'Updated Test Contact' still exists in the database.");
                    Console.WriteLine("{0,-30} {1,-20} {2,-20} {3,-30}", "Name", "Work Phone", "City", "Email");
                    Console.WriteLine(new string('-', 100));
                    Console.WriteLine("{0,-30} {1,-20} {2,-20} {3,-30}", deletedContact.Name, deletedContact.WorkPhone, deletedContact.City, deletedContact.Email);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

You can see that all test rows have been deleted.

Result with the deleted rows

Conclusion

By combining dotConnect for SugarCRM with Dapper, you get the speed of raw SQL and the flexibility of CRM integration—without manual handling of API calls. It's a streamlined solution for building efficient, database-style access to SugarCRM
data in C#.

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