📜  aquarette - C# (1)

📅  最后修改于: 2023-12-03 14:59:22.042000             🧑  作者: Mango

aquarette - C#介绍

aquarette

aquarette是一款基于C#语言开发的轻量级ORM框架,旨在简化开发人员与数据库之间的交互。

特性
  • 支持MSSQL、MySQL、PostgreSQL、SQLite等主流数据库;
  • 操作简单,使用方便;
  • 支持LINQ查询语义;
  • 自动映射实体和数据库表结构;
  • 支持事务处理;
  • 支持自定义SQL查询和存储过程调用;
安装

你可以通过NuGet包管理器进行安装:

Install-Package aquarette
快速入门
连接数据库

在使用aquarette前,请确保先进行有效的数据库连接。示例代码如下:

string connectionString = "server=localhost;uid=user;pwd=123456;database=mydb;"
var context = new DbContext(connectionString);
创建实体对象

在aquarette中,你需要定义实体对象来映射数据库表结构。

例如下面我们定义了一个叫做"Customer"的实体对象:

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}
操作实体对象

插入

我们可以使用Insert方法插入数据:

Customer customer = new Customer() { Name = "Mike", Email = "mike@example.com" };
context.Insert(customer);

更新

我们可以使用Update方法更新数据:

Customer customer = context.Query<Customer>().Where(c => c.Name == "Mike").FirstOrDefault();
if (customer != null)
{
    customer.Email = "newemail@example.com";
    context.Update(customer);
}

删除

我们可以使用Delete方法删除数据:

Customer customer = context.Query<Customer>().Where(c => c.Name == "Mike").FirstOrDefault();
if (customer != null)
{
    context.Delete(customer);
}

查询

我们可以使用Query方法查询数据,此外,我们也可以使用LINQ查询语义:

List<Customer> customers = context.Query<Customer>().ToList();
Customer customer = context.Query<Customer>().Where(c => c.Id == 1).FirstOrDefault();
更多用例
使用事务

我们可以使用Transaction方法启动一个事务:

using (var transaction = context.Transaction())
{
    try
    {
        Customer customer1 = new Customer() { Name = "Mike", Email = "mike@example.com" };
        context.Insert(customer1);

        Customer customer2 = new Customer() { Name = "John", Email = "john@example.com" };
        context.Insert(customer2);

        transaction.Commit();
    }
    catch (Exception)
    {
        transaction.Rollback();
    }
}
自定义SQL查询和存储过程调用

我们可以使用Execute方法来自定义SQL查询和存储过程调用,示例代码如下:

List<Customer> customers = context.Execute<Customer>("SELECT * FROM Customer", CommandType.Text);
int count = context.Execute<int>("SELECT COUNT(*) FROM Customer", CommandType.Text).FirstOrDefault();
string name = context.Execute<string>("usp_GetCustomerName", CommandType.StoredProcedure, new SqlParameter("@CustomerId", 1)).FirstOrDefault();
结论

aquarette是一款轻量级且易于使用的ORM框架,并且支持多种主流数据库。如果你正在寻找一个简单而又高效的ORM框架,那么aquarette将是你不错的选择。