SqlSugar is a feature-rich and user-friendly ORM framework for the .NET platform. This topic shows you how to connect to OceanBase Database's MySQL-compatible mode using SqlSugar.
Prerequisites
- You have installed .NET SDK 6.0 or later.
- You have installed Visual Studio or VS Code.
- You have deployed OceanBase Database and created a MySQL-compatible tenant.
Procedure
- Create a new project.
- Install the necessary NuGet packages.
- Configure the database connection.
- Create a data model.
- Implement the data access layer.
- Run the sample program.
Step 1: Create a new project
Open your terminal and run the following commands to create a new console application:
dotnet new console -n SqlSugarOceanBaseDemo
cd SqlSugarOceanBaseDemo
Step 2: Install necessary NuGet packages
Install SqlSugar, the MySQL database provider, and other dependencies:
# ORM core package
dotnet add package SqlSugarCore
# Database provider
dotnet add package MySql.Data
# Configuration-related packages
dotnet add package Microsoft.Extensions.Configuration --version 8.0.0
dotnet add package Microsoft.Extensions.Configuration.FileExtensions --version 8.0.0
dotnet add package Microsoft.Extensions.Configuration.Json --version 8.0.0
# Password encryption
dotnet add package BCrypt.Net-Next --version 4.0.3
Step 3: Configure the database connection
Create an
appsettings.jsonfile and add the database connection string:{ "ConnectionStrings": { "DefaultConnection": "Server=your_server;Port=2881;Database=your_database;Uid=your_username;Pwd=your_password;" } }Modify the project file (
.csproj) to ensure thatappsettings.jsonis copied to the output directory:<ItemGroup> <None Update="appsettings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup>
Step 4: Create a data model
Create a Models folder and add a User.cs class:
using SqlSugar;
namespace SqlSugarOceanBaseDemo.Models;
[SugarTable("users")]
public class User
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
[SugarColumn(Length = 50, IsNullable = false)]
public string Username { get; set; }
[SugarColumn(Length = 100, IsNullable = false)]
public string Email { get; set; }
[SugarColumn(Length = 255, IsNullable = false)]
public string PasswordHash { get; set; }
[SugarColumn(IsNullable = false)]
public DateTime CreatedAt { get; set; }
[SugarColumn(IsNullable = true)]
public DateTime? UpdatedAt { get; set; }
}
Step 5: Implement the data access layer
Create a
Servicesfolder and add aDatabaseContext.csclass:using Microsoft.Extensions.Configuration; using SqlSugar; using System; using System.IO; namespace SqlSugarOceanBaseDemo.Services; public class DatabaseContext { public SqlSugarScope Db { get; private set; } public DatabaseContext(IConfiguration configuration) { Db = new SqlSugarScope(new ConnectionConfig() { ConnectionString = configuration.GetConnectionString("DefaultConnection"), DbType = DbType.MySql, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute }, db => { db.Aop.OnLogExecuting = (sql, pars) => { Console.WriteLine($"SQL: {sql}"); if (pars != null) { foreach (var param in pars) { Console.WriteLine($" -> {param.ParameterName}: {param.Value}"); } } }; db.Aop.OnError = (exp) => { Console.WriteLine($"Error: {exp.Message}"); return true; }; db.Aop.OnLogExecuted = (sql, pars) => { Console.WriteLine($"Execution time: {db.Ado.SqlExecutionTime.TotalMilliseconds}ms"); }; db.InitKeyType = InitKeyType.Attribute; }; Db.CodeFirst.InitTables(typeof(Models.User)); } }Create a
Repositoriesfolder and add aUserRepository.csclass:using SqlSugar; using SqlSugarOceanBaseDemo.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace SqlSugarOceanBaseDemo.Repositories; public class UserRepository { private readonly ISqlSugarClient _db; public UserRepository(ISqlSugarClient db) { _db = db; } public async Task<List<User>> GetAllUsersAsync() { return await _db.Queryable<User>().ToListAsync(); } public async Task<User> GetUserByIdAsync(int id) { return await _db.Queryable<User>().FirstAsync(u => u.Id == id); } public async Task<int> CreateUserAsync(User user) { user.CreatedAt = DateTime.UtcNow; return await _db.Insertable(user).ExecuteReturnIdentityAsync(); } public async Task<bool> UpdateUserAsync(User user) { user.UpdatedAt = DateTime.UtcNow; return await _db.Updateable(user).ExecuteCommandHasChangeAsync(); } public async Task<bool> DeleteUserAsync(int id) { return await _db.Deleteable<User>().Where(u => u.Id == id).ExecuteCommandHasChangeAsync(); } }
Step 6: Implement the main program
Modify the Program.cs file:
using Microsoft.Extensions.Configuration;
using SqlSugarOceanBaseDemo.Models;
using SqlSugarOceanBaseDemo.Repositories;
using SqlSugarOceanBaseDemo.Services;
using System;
using System.IO;
using System.Threading.Tasks;
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
var dbContext = new DatabaseContext(configuration);
var userRepository = new UserRepository(dbContext.Db);
var newUser = new User
{
Username = "testuser",
Email = "test@example.com",
PasswordHash = BCrypt.Net.BCrypt.HashPassword("your_secure_password")
};
try
{
var createdUser = await userRepository.CreateUserAsync(newUser);
Console.WriteLine($"User created with ID: {createdUser.Id}");
var user = await userRepository.GetUserByIdAsync(createdUser.Id);
if (user != null)
{
Console.WriteLine($"Retrieved user: {user.Username}, Email: {user.Email}");
user.Username = "updated_username";
var updated = await userRepository.UpdateUserAsync(user);
Console.WriteLine($"User updated: {updated}");
var users = await userRepository.GetAllUsersAsync();
Console.WriteLine($"Total users: {users.Count}");
var deleted = await userRepository.DeleteUserAsync(user.Id);
Console.WriteLine($"User deleted: {deleted}");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
Run the program
Make sure your database connection string in
appsettings.jsonis up to date.In your terminal, run:
dotnet run