OceanBase logo

OceanBase

A unified distributed database ready for your transactional, analytical, and AI workloads.

Product Overview
DEPLOY YOUR WAY

OceanBase Cloud

The best way to deploy and scale OceanBase

OceanBase Enterprise

Run and manage OceanBase on your infra

TRY OPEN SOURCE

OceanBase Community Edition

The free, open-source distributed database

OceanBase seekdb

Open source AI native search database

Customer Stories

Real-world success stories from enterprises across diverse industries.

View All
BY USE CASES

Mission-Critical Transactions

Global & Multicloud Application

Elastic Scaling for Peak Traffic

Real-time Analytics

Active Geo-redundancy

Database Consolidation

Resources

Comprehensive knowledge hub for OceanBase.

Blog

Live Demos

Training & Certification

Documentation

Official technical guides, tutorials, API references, and manuals for all OceanBase products.

View All
PRODUCTS

OceanBase Cloud

OceanBase Database

Tools

Connectors and Middleware

QUICK START

OceanBase Cloud

OceanBase Database

BEST PRACTICES

Practical guides for utilizing OceanBase more effectively and conveniently

Company

Learn more about OceanBase – our company, partnerships, and trust and security initiatives.

About OceanBase

Partner

Trust Center

Contact Us

International - English
中国站 - 简体中文
日本 - 日本語
Sign In
Start on Cloud

OceanBase

A unified distributed database ready for your transactional, analytical, and AI workloads.

Product Overview
DEPLOY YOUR WAY

OceanBase Cloud

The best way to deploy and scale OceanBase

OceanBase Enterprise

Run and manage OceanBase on your infra

TRY OPEN SOURCE

OceanBase Community Edition

The free, open-source distributed database

OceanBase seekdb

Open source AI native search database

Customer Stories

Real-world success stories from enterprises across diverse industries.

View All
BY USE CASES

Mission-Critical Transactions

Global & Multicloud Application

Elastic Scaling for Peak Traffic

Real-time Analytics

Active Geo-redundancy

Database Consolidation

Comprehensive knowledge hub for OceanBase.

Blog

Live Demos

Training & Certification

Documentation

Official technical guides, tutorials, API references, and manuals for all OceanBase products.

View All
PRODUCTS
OceanBase CloudOceanBase Database
ToolsConnectors and Middleware
QUICK START
OceanBase CloudOceanBase Database
BEST PRACTICES

Practical guides for utilizing OceanBase more effectively and conveniently

Learn more about OceanBase – our company, partnerships, and trust and security initiatives.

About OceanBase

Partner

Trust Center

Contact Us

Start on Cloud
编组
All Products
    • Databases
    • iconOceanBase Database
    • iconOceanBase Cloud
    • iconOceanBase Tugraph
    • iconInteractive Tutorials
    • iconOceanBase Best Practices
    • Tools
    • iconOceanBase Cloud Platform
    • iconOceanBase Migration Service
    • iconOceanBase Developer Center
    • iconOceanBase Migration Assessment
    • iconOceanBase Admin Tool
    • iconOceanBase Loader and Dumper
    • iconOceanBase Deployer
    • iconKubernetes operator for OceanBase
    • iconOceanBase Diagnostic Tool
    • iconOceanBase Binlog Service
    • Connectors and Middleware
    • iconOceanBase Database Proxy
    • iconEmbedded SQL in C for OceanBase
    • iconOceanBase Call Interface
    • iconOceanBase Connector/C
    • iconOceanBase Connector/J
    • iconOceanBase Connector/ODBC
    • iconOceanBase Connector/NET
icon

OceanBase Database

SQL - V4.4.2

    Download PDF

    OceanBase logo

    The Unified Distributed Database for the AI Era.

    Follow Us
    Products
    OceanBase CloudOceanBase EnterpriseOceanBase Community EditionOceanBase seekdb
    Resources
    DocsBlogLive DemosTraining & CertificationTicket
    Company
    About OceanBaseTrust CenterLegalPartnerContact Us
    Follow Us

    © OceanBase 2026. All rights reserved

    Cloud Service AgreementPrivacy PolicySecurity
    Contact Us
    Document Feedback
    1. Documentation Center
    2. OceanBase Database
    3. SQL
    4. V4.4.2
    iconOceanBase Database
    SQL - V 4.4.2
    Databases
    • OceanBase Database
    • OceanBase Cloud
    • OceanBase Tugraph
    • Interactive Tutorials
    • OceanBase Best Practices
    Tools
    • OceanBase Cloud Platform
    • OceanBase Migration Service
    • OceanBase Developer Center
    • OceanBase Migration Assessment
    • OceanBase Admin Tool
    • OceanBase Loader and Dumper
    • OceanBase Deployer
    • Kubernetes operator for OceanBase
    • OceanBase Diagnostic Tool
    • OceanBase Binlog Service
    Connectors and Middleware
    • OceanBase Database Proxy
    • Embedded SQL in C for OceanBase
    • OceanBase Call Interface
    • OceanBase Connector/C
    • OceanBase Connector/J
    • OceanBase Connector/ODBC
    • OceanBase Connector/NET
    SQL
    KV
    • V 4.6.0
    • V 4.4.2
    • V 4.3.5
    • V 4.3.3
    • V 4.3.1
    • V 4.3.0
    • V 4.2.5
    • V 4.2.2
    • V 4.2.1
    • V 4.2.0
    • V 4.1.0
    • V 4.0.0
    • V 3.1.4 and earlier

    Connect to OceanBase Database by using FreeSQL

    Last Updated:2026-04-09 08:31:39  Updated
    Share
    What is on this page
    Prerequisites
    Procedure
    Step 1: Create a new project
    Step 2: Install the necessary NuGet packages
    Step 3: Configure the database connection
    Step 4: Create a data model
    Step 5: Implement the data access layer
    Step 6: Implement the main program
    Run the program
    References

    folded

    Share

    FreeSQL is a powerful and flexible ORM framework for .NET and supports multiple databases. This topic walks you through connecting to OceanBase Database's MySQL-compatible mode using FreeSQL.

    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

    1. Create a new project.
    2. Install the necessary NuGet packages.
    3. Configure the database connection.
    4. Create a data model.
    5. Implement the data access layer.
    6. 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 FreeSQLOceanBaseDemo
    cd FreeSQLOceanBaseDemo
    

    Step 2: Install the necessary NuGet packages

    Install FreeSQL and the required dependencies:

    # ORM core package
    dotnet add package FreeSQL
    dotnet add package FreeSql.Provider.MySqlConnector
    dotnet add package FreeSql.DbContext
    
    # 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

    1. Create an appsettings.json file and add the database connection string:

      {
        "ConnectionStrings": {
          "DefaultConnection": "Server=your_server;Port=2881;Database=your_database;Uid=your_username;Pwd=your_password;"
        }
      }
      
    2. Modify the project file (.csproj) to ensure that appsettings.json is 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 FreeSql.DataAnnotations;
    using System;
    
    namespace FreeSQLOceanBaseDemo.Models;
    
    [Table(Name = "users")]
    public class User
    {
        [Column(IsPrimary = true, IsIdentity = true)]
        public int Id { get; set; }
    
        [Column(StringLength = 50, IsNullable = false)]
        public string Username { get; set; }
    
        [Column(StringLength = 100, IsNullable = false)]
        public string Email { get; set; }
    
        [Column(StringLength = 255, IsNullable = false)]
        public string PasswordHash { get; set; }
    
        [Column(ServerTime = DateTimeKind.Utc, CanUpdate = false)]
        public DateTime CreatedAt { get; set; }
    
        [Column(ServerTime = DateTimeKind.Utc)]
        public DateTime? UpdatedAt { get; set; }
    }
    

    Step 5: Implement the data access layer

    1. Create a Data folder and add an AppDbContext.cs class:

      using FreeSql;
      using System.Data;
      using FreeSql.DatabaseModel;
      using FreeSQLOceanBaseDemo.Models;
      using Microsoft.Extensions.Configuration;
      using System;
      using System.IO;
      namespace FreeSQLOceanBaseDemo.Data;
      public class AppDbContext : DbContext
      {
      public DbSet Users { get; set; }
      private readonly IConfiguration _configuration;
      private static IFreeSql _fsql;
      public AppDbContext(IConfiguration configuration)
      {
      _configuration = configuration;
      
      if (_fsql == null)
      {
          _fsql = new FreeSqlBuilder()
              .UseConnectionString(DataType.MySql, _configuration.GetConnectionString("DefaultConnection"))
              .UseMonitorCommand(cmd =>
              {
                  Console.WriteLine($"SQL: {cmd.CommandText}");
                  if (cmd.Parameters != null)
                  {
                      foreach (IDataParameter param in cmd.Parameters)
                      {
                          Console.WriteLine($"  -> {param.ParameterName}: {param.Value}");
                      }
                  }
              })
              .UseAutoSyncStructure(true)
              .Build();
      
          _fsql.Aop.CurdBefore += (s, e) =>
          {
              Console.WriteLine($"Execution before: {e.Sql}");
          };
      
          _fsql.Aop.CurdAfter += (s, e) =>
          {
              Console.WriteLine($"Execution after, affected rows: {e.ElapsedMilliseconds}ms");
          };
      }
      }
      public IFreeSql GetFreeSql()
      {
      return _fsql;
      }
      }
      
    2. Create a Repositories folder and add a UserRepository.cs class:

      using FreeSql;
      using FreeSQLOceanBaseDemo.Models;
      using System;
      using System.Collections.Generic;
      using System.Threading.Tasks;
      
      namespace FreeSQLOceanBaseDemo.Repositories;
      
      public class UserRepository
      {
          private readonly IFreeSql _fsql;
      
          public UserRepository(IFreeSql fsql)
          {
              _fsql = fsql;
          }
      
          public async Task<List<User>> GetAllUsersAsync()
          {
              return await _fsql.Select<User>().ToListAsync();
          }
      
          public async Task<User> GetUserByIdAsync(int id)
          {
              return await _fsql.Select<User>().Where(u => u.Id == id).FirstAsync();
          }
      
          public async Task<User> CreateUserAsync(User user)
          {
              user.CreatedAt = DateTime.UtcNow;
              await _fsql.Insert(user).ExecuteAffrowsAsync();
              return user;
          }
      
          public async Task<bool> UpdateUserAsync(User user)
          {
              user.UpdatedAt = DateTime.UtcNow;
              var result = await _fsql.Update<User>()
                  .SetSource(user)
                  .ExecuteAffrowsAsync();
      
              return result > 0;
          }
      
          public async Task<bool> DeleteUserAsync(int id)
          {
              var result = await _fsql.Delete<User>()
                  .Where(u => u.Id == id)
                  .ExecuteAffrowsAsync();
      
              return result > 0;
          }
      }
      

    Step 6: Implement the main program

    Modify the Program.cs file:

    using FreeSQLOceanBaseDemo.Data;
    using FreeSQLOceanBaseDemo.Models;
    using FreeSQLOceanBaseDemo.Repositories;
    using Microsoft.Extensions.Configuration;
    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 AppDbContext(configuration);
    var userRepository = new UserRepository(dbContext.GetFreeSql());
    
    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}");
        Console.WriteLine(ex.StackTrace);
    }
    

    Run the program

    1. Make sure your database connection string in appsettings.json is up to date.

    2. In your terminal, run:

      dotnet run
      

    References

    • FreeSQL Documentation
    • .NET database access best practices
    • OceanBase Documentation

    Previous topic

    SqlSugar
    Last

    Next topic

    Yii 2.0 ORM
    Next
    What is on this page
    Prerequisites
    Procedure
    Step 1: Create a new project
    Step 2: Install the necessary NuGet packages
    Step 3: Configure the database connection
    Step 4: Create a data model
    Step 5: Implement the data access layer
    Step 6: Implement the main program
    Run the program
    References