輕量級.NET CORE ORM框架Insql使用教程


Insql 國人開發,是一款汲取 Mybatis 優點的.NET ORM 框架。追求簡單直觀,使用自由靈活等特點。

項目主頁:https://rainrcn.github.io/insql

此 ORM 是以 Mybatis 的 Sql 配置方式,以 Dapper 為對象映射的基礎上建立。喜歡寫 SQL 的同學們肯定會喜歡的。另外因為對象映射使用 Dapper 的關系,所以性能上不用過多擔心。

創建項目

模板選擇ApiWeb應用程序,如果會自己大家結構選擇也是可以的。

在項目上鼠標右鍵選擇管理Nuget程序包,搜索Insql並添加安裝,Insql 包自帶 SqlServer 數據庫連接,如果需要 MySql 數據庫,需要另外安裝Insql.MySql

使用

打開Startup.cs,在ConfigureServices中加入AddInsql

public void ConfigureServices(IServiceCollection services)
{
    services.AddInsql();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

Insql 就已經可以開始用了。

在項目下創建Domain目錄,並創建UserDbContext.cs UserDbContext.insql.xml UserPo.cs RolePo.cs 文件

UserDbContext.insql.xml 要右鍵屬性選擇嵌入式資源

寫代碼

1. 創建數據庫模型類 UserPo.cs RolePo.cs

public class UserPo
{
    public string UserId { get; set; }

    public string UserName { get; set; }

    public DateTime CreateTime { get; set; }
}

public class RolePo
{
    public string RoleCode { get; set; }

    public string RoleName { get; set; }

    public int RoleOrder { get; set; }
}

2. 創建UseDbContext.insql.xmlSQL 配置

<insql type="InsqlExample.Domain.Context.UserDbContext,InsqlExample" >

  <!--定義UserPo類型數據庫字段到對象屬性映射-->
  <map type="InsqlExample.Domain.Model.UserPo,InsqlExample">
    <key name="user_id" to="UserId" />
    <column name="user_name" to="UserName" />
    <column name="create_time" to="CreateTime" />
  </map>

  <map type="InsqlExample.Domain.Model.RolePo,InsqlExample">
    <key name="role_code" to="RoleCode" />
    <column name="role_name" to="RoleName" />
    <column name="role_order" to="RoleOrder" />
  </map>

  <select id="GetUser">
    select * from user_info where user_id = @userId
  </select>

  <insert id="InsertUser">
    insert into user_info (user_id,user_name,create_time) value (@UserId,@UserName,@CreateTime)
  </insert>

  <update id="UpdateUser">
    update user_info
    <set>
      <if test="UserName != null">
        user_name = @UserName,
      </if>
    </set>
    where user_id = @UserId
  </update>

  <delete id="DeleteUser">
    delete from user_info where user_id = @userId
  </delete>

  <select id="GetRoleList">
    select * from role_info order by role_order
  </select>
</insql>

select,insert,update,delete 分別代表增刪改查,可以看到在update中有特殊 xml 元素,可以進項目文檔查看詳細說明,有 Mybatis 經驗的同學自然就理解了

3. 創建UserDbContext數據上下文

public class UserDbContext : DbContext
{
    public UserDbContext(DbContextOptions<UserDbContext> options) : base(options)
    {
    }

    public UserPo GetUser(string userId)
    {
        //"GetUser"對應 select上的id,
        //第二個查詢參數支持 PlainObject和 IDictionary<string,object>兩種類型
        return this.Query<UserPo>("GetUser", new { userId }).SingleOrDefault();
    }

    public void InsertUser(UserPo user)
    {
        this.Execute(nameof(InsertUser), user);
    }

    public void UpdateUser(UserPo user)
    {
        this.Execute(nameof(UpdateUser), user);
    }

    public void DeleteUser(string userId)
    {
        this.Execute(nameof(DeleteUser), new { userId });
    }

    public IEnumerable<RolePo> GetRoleList()
    {
        return this.Query<RolePo>("GetRoleList");
    }
}

別忘了在Startup.cs中注冊 UserDbContext。 命名空間 using Insql;一下

public void ConfigureServices(IServiceCollection services)
{
    services.AddInsql();

    services.AddInsqlDbContext<UserDbContext>(options =>
    {
        //這里代表這個上下文使用這個SqlServer數據庫
        options.UseSqlServer("這里是連接字符串");
    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

增刪改查這就 OK 了。然后我們可以在 Controller 或者 Service 中直接注入 UserDbContext 來用。

4. 在ValuesController.cs中使用UserDbContext

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly UserDbContext dbContext;

    public ValuesController(UserDbContext dbContext)
    {
        this.dbContext = dbContext;
    }

    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        //查詢用戶
        var user1 = this.dbContext.GetUser("tome");

        //增加用戶
        this.dbContext.InsertUser(new UserPo
        {
            UserId = Guid.NewGuid().ToString(),
            UserName = "tom",
            CreateTime = DateTime.Now
        });

        //查詢角色列表
        var roleList = this.dbContext.GetRoleList();

        //....其他的不演示了

        //還可以這樣用,通過dbContext直接調用sql,和在DbContext里面寫方法一樣的
        var userJerry = this.dbContext.Query<UserPo>("GetUser", new { userId = "jerry" });

        return new string[] { "value1", "value2" };
    }
}

行這就完事了。

可以去看看項目文檔,支持功能還挺多的。代碼生成器也有。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM