How to Connect to SugarCRM in .NET With C#

SugarCRM is a widely used customer relationship management (CRM) platform known for its robust functionality, flexibility, and high level of customization. It is an enterprise-grade system available both on-premises and in the cloud, designed to meet the needs of businesses of all sizes.

SugarCRM is often used as part of the backend infrastructure for many data-driven applications. With modern development technologies, building such applications has become faster and more efficient. However, one of the main challenges for developers is establishing a stable, secure, and reliable connection to access and manipulate data in SugarCRM from their applications. This tutorial will guide you through the process of connecting to SugarCRM from .NET applications using C# and dotConnect for SugarCRM.

Why dotConnect for SugarCRM?

dotConnect for SugarCRM is a powerful and easy-to-use data provider that enables direct data access and operations in SugarCRM without the need for additional client libraries or complex configurations.

With its straightforward connector setup, flexibility, seamless Visual Studio integration, and advanced ORM support, dotConnect greatly enhances application performance and functionality. It also simplifies the workflow for .NET developers who need to access and manage SugarCRM data efficiently.

Prerequisites

The following prerequisites are necessary to follow this guide:

  • Visual Studio 2022:Our IDE of choice. If you do not have it on your machine, visit the official website and install the free Community Edition.
  • dotConnect for SugarCRM: A robust ADO.NET data provider for SugarCRM with EF Core (Entity Framework), Dapper, NHibernate, and LinqConnect support.
  • Entity Developer: An ORM designer for .NET ORM Frameworks with powerful code generation capabilities.

Download and activate dotConnect for SugarCRM

Depending on your conditions, you may choose a fully-functional free trial or a full version.

30-day free trial version

You can start using dotConnect for SugarCRM immediately with a 30-day free trial. Choose one of the installation options.

No license key is necessary for the trial version — just install it and explore.

Full version

After purchasing the full version, follow these steps:

1. Go to the Products section in your Devart profile.

2. Click the product name, or hover over it and click Details. The License details page opens. Find the Activation Key:

License details and the activation key

3. To activate dotConnect for PostgreSQL in your application, copy the Activation Key and paste it into your connection string as the License Key parameter.

Create a .NET Core project

To illustrate our tutorial, we need a demo application that will connect to SugarCRM and access the SugarCRM data. Let us create a simple console application in Visual Studio and install the required NuGet packages for dotConnect.

1. Launch Visual Studio and click Create a new project.

2. Choose Console App (.NET Core) and click Next.

3. Give this project a name (in our tutorial, we name it SugarConnect), specify the path to its folder, and click Create.

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

5. Go to the Browse tab, find and install the following packages:

Connect to SugarCRM using C#

After creating the console application, use the code below to ensure the connection to SugarCRM is successful.

Note
Make sure to replace user id, password, and host with your actual SugarCRM credentials and URL.
using System;
using Devart.Data.Sugar;

namespace SugarConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "" +
                "Host=https://test.sugaropencloud.eu;" +
                "User Id=TestUser;" +
                "Password=TestPassword;" +
                "License Key=**********";

            try
            {
                using (var conn = new SugarConnection(connectionString))
                {
                    conn.Open();
                    using (var cmd = (SugarCommand)conn.CreateCommand())
                    {
                        cmd.CommandText = "SELECT Id, Name FROM Accounts";
                        using (var reader = cmd.ExecuteReader())
                        {
                            int count = 0;
                            while (reader.Read() && count < 15)
                            {
                                Console.WriteLine($"Id: {reader["Id"]}");
                                Console.WriteLine($"Name: {reader["Name"]}");
                                Console.WriteLine();
                                count++;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
    }
}

When connected, the application fetches the first eight rows from the role table and displays them in the console.

Connect to SugarCRM using C# and view the data

Connect using Server Explorer

Another option available for connecting to SugarCRM is via the Server Explorer in Visual Studio. Right-click Data Connections and select Add Connection from the context menu.

Add a new connection to SugarCRM

The Change Data Source dialog window opens. Select dotConnect for SugarCRM from the list of installed data providers.

Choose dotConnect for SugarCRM as a data source

Fill in the necessary connection properties and click Test Connection to verify the settings. Now you can connect to SugarCRM.

Connect to SugarCRM via Server Explorer in Visual Studio

Expand the newly created data connection in the Server Explorer. You can view the data source structure, including all tables and table columns. To display data from a particular table, right-click it and select Retrieve Data from Table. This opens a new query window with a SELECT statement.

View the SugarCRM data in Server Explorer

Connect with EF Core using Entity Developer

Entity Developer is a visual ORM builder that allows developers to create EF Core models using SugarCRM data.

Right-click the solution and navigate to Add > New Item.

Add new item for SugarCRM

Select Data and choose Devart EF Core Model.

Start creating the Devart EF Core Model

The Entity Developer Model wizard opens. Select Database First and click Next.

Choose the Database First approach in Entity Developer

Enter your connection details for SugarCRM, click Test Connection to verify them, and click Next to proceed.

Provide the connection details for SugarCRM

In the Choose Model Contents window, select Generate From Database. Click Next.

Generate model contents from database

In the Select database objects window, define the objects to scaffold.

Select database objects to include in the model

Define the naming convention for the database object property names to follow. In this tutorial, we keep the default settings. Click Next.

Specify the naming rules in the wizard

Set up the model properties, such as the namespace and entity container.

Configure the model properties

Choose the contents of the Model Diagram. You can include all entities, split them by database, or select custom ones as needed. In this tutorial, we include all entities in the diagram.

Choose the entities to include in the model diagram

Finally, choose the Code Generation Templates for the model. You can define various parameters as required.

Choose and configure model code generation templates

The model is ready. You can download Devart.Data.Sugar.EFCore if needed. Click Finish.

Finish the Entity Developer model creation

View the generated model. You can start working with it immediately.

View the generated data model in Visual Studio

Also, you can see the generated DbContext files in Visual Studio under the model.

View the generated DbContext files

To read the SugarCRM data using EF Core, execute the code below.

using SugarConnect;
using Devart.Data.Sugar;
using Microsoft.EntityFrameworkCore;

namespace SugarConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder();
            optionsBuilder.UseSugar(ConfigurationHelper.ConnectionString);

            using (var context = new sugarModel(optionsBuilder.Options))
            {
                var query = from acc in context.Accounts
                            orderby acc.Name
                            select acc;

                foreach (var account in query.Take(10).ToList())
                {
                    Console.WriteLine($"{account.Id} | {account.Name}");
                }
            }

            Console.ReadLine();
        }
    }
}

You can view the result in your console application.

Read the SugarCRM data and display it in the application

Connect with EF Core using Scaffold-DbContext

One more connection method you can use to access your SugarCRM data is via Entity Framework Core (EF Core) and the Scaffold-DbContext command. We will generate the necessary EF Core model classes and DbContext based on the existing database schema.

First of all, let us install the required NuGet packages via the Solution Explorer in Visual Studio as described earlier:

After that, open the Package Manager Console: Tools > NuGet Package Manager > Package Manager Console and 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 "Host=https://test.sugaropencloud.eu;User Id=TestUser;Password=TestPassword;License Key=******;" Devart.Data.Sugar.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

This tutorial has demonstrated several methods for connecting to SugarCRM and accessing its data. You can choose the approach that best fits your project requirements and development scenarios when building applications that use SugarCRM as part of their backend.

dotConnect for SugarCRM provides a fast and straightforward way to establish a connection, while Entity Developer allows you to visually design data models and take full advantage of popular ORM frameworks with ease.

Both dotConnect for SugarCRM and Entity Developer offer fully functional free trials, allowing you to integrate them into your workflow and evaluate their capabilities firsthand.

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