3. FreeSql在ASP.NTE Core WebApi中如何使用的教程

文章概述

主要在介紹FreeSql在ASP.NTE Core WebApi中如何使用的過(guò)程,完成一個(gè)最簡(jiǎn)單的博客系統(tǒng)的后端接口。

FreeSql 簡(jiǎn)介

國(guó)人寫的一個(gè)功能強(qiáng)大的ORM,FreeSql 支持 MySql/SqlServer/PostgreSQL/Oracle/Sqlite,特點(diǎn):輕量級(jí)、可擴(kuò)展、基于 .NET Standard 跨平臺(tái)。

參考

項(xiàng)目準(zhǔn)備

  • Mysql 5.6
  • Visual Studio 2019或2017、Visual Studio code
  • .NET Core 2.2+
  • PowerShell
  • 懂點(diǎn)mvc,該教程不會(huì)教你如何使用 ASP .NET Core MVC、RESTful

創(chuàng)建一個(gè)webapi 的項(xiàng)目,起名為WebAPI.FreeSql

PS dotnetcore-examples\WebAPI-FreeSql> dotnet new webapi -n Webapi.FreeSql
The template "ASP.NET Core Web API" was created successfully.
PS dotnetcore-examples\WebAPI-FreeSql> cd .\Webapi.FreeSql\
PS dotnetcore-examples\WebAPI-FreeSql\Webapi.FreeSql> dotnet run

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: D:\code\github\dotnetcore-examples\WebAPI-FreeSql\Webapi.FreeSql

打開瀏覽器 https://localhost:5001 會(huì)出現(xiàn)404

請(qǐng)打開這個(gè)地址 https://localhost:5001/api/values ,可看到如下內(nèi)容。

["value1","value2"]

接下來(lái)我們來(lái)集成FreeSql,我們以最簡(jiǎn)單的命令和說(shuō)明,詳細(xì)內(nèi)容去官網(wǎng)看具體內(nèi)容

Install

要先cd到Webapi.FreeSql目錄中。

PS \WebAPI-FreeSql\Webapi.FreeSql> dotnet add package FreeSql
PS \WebAPI-FreeSql\Webapi.FreeSql> dotnet add package FreeSql.Provider.MySql

code first

代碼優(yōu)先,使用過(guò)EntityFramework的應(yīng)該很清楚這一概念,我的理解就是:在分析數(shù)據(jù)庫(kù)表關(guān)系時(shí),不通過(guò)在數(shù)據(jù)庫(kù)中設(shè)計(jì)表,而是直接在代碼中聲明對(duì)應(yīng)的類,使用導(dǎo)航屬性代替外鍵關(guān)聯(lián),通過(guò)數(shù)據(jù)表字段與C#中的類庫(kù)對(duì)應(yīng),從而自動(dòng)生成數(shù)據(jù)表。

db first

數(shù)據(jù)庫(kù)優(yōu)先:需求分析后,直接設(shè)計(jì)數(shù)據(jù)庫(kù),通過(guò)數(shù)據(jù)庫(kù)中的表,直接生成代碼,類。

開始

分析需求

我們以code first 為示例,學(xué)習(xí)如何使用freesql,實(shí)現(xiàn)一個(gè)簡(jiǎn)單的博客。將表內(nèi)容分為博客表(Blog)和評(píng)論表(Post)

Blog 表

字段名 字段類型 說(shuō)明
BlogId int 博客id
Title varchar(50) 博客標(biāo)題
Content varchar(500) 博客內(nèi)容
CreateTime DateTime 發(fā)布時(shí)間

Post 表

字段名 字段類型 說(shuō)明
PostId int 評(píng)論id
ReplyContent varchar(50) 標(biāo)題
BlogId int 博客id
ReplyTime DateTime 回復(fù)時(shí)間

建一個(gè)Domain文件夾,用于存放數(shù)據(jù)庫(kù)表中對(duì)應(yīng)的實(shí)體類。

關(guān)于

1. Column屬性介紹,大家可以看源碼,解析

1). 比如:Blog表中指定了Title為varchar(50),我們?nèi)绾瓮ㄟ^(guò)代碼指定了主鍵,唯一值,字形。

    public class Blog
    {
        [Column(IsIdentity = true, IsPrimary = true)]
        public int BlogId { get; set; }
        [Column(DbType = "varchar(50)")]
        public string Title { get; set; }
    }

2). Column的命名空間在

using FreeSql.DataAnnotations;

更多屬性介紹

字段 備注
Name 數(shù)據(jù)庫(kù)列名
OldName 指定數(shù)據(jù)庫(kù)舊的列名,修改實(shí)體屬性命名時(shí),同時(shí)設(shè)置此參數(shù)為修改之前的值,CodeFirst才可以正確修改數(shù)據(jù)庫(kù)字段;否則將視為【新增字段】
DbType 數(shù)據(jù)庫(kù)類型,如: varchar(255)
IsPrimary 主鍵
IsIdentity 自增標(biāo)識(shí)
IsNullable 是否可DBNull
IsIgnore 忽略此列,不遷移、不插入
IsVersion 設(shè)置行鎖(樂(lè)觀鎖)版本號(hào),每次更新累加版本號(hào),若更新整個(gè)實(shí)體時(shí)會(huì)附帶當(dāng)前的版本號(hào)判斷(修改失敗時(shí)拋出異常)
DbDefautValue 數(shù)據(jù)庫(kù)默認(rèn)值
MapType 類型映射,比如:可將 enum 屬性映射成 typeof(string)
Uniques 唯一鍵,在多個(gè)屬性指定相同的標(biāo)識(shí),代表聯(lián)合鍵;可使用逗號(hào)分割多個(gè) UniqueKey 名。

2. Table 的使用:用于在類的上面指定這個(gè)表的屬性

[Table(Name = "t_blog")]
public class Blog {
  //...
}

更多屬性介紹

字段 備注
Name 數(shù)據(jù)庫(kù)表名
OldName 指定數(shù)據(jù)庫(kù)舊的表名,修改實(shí)體命名時(shí),同時(shí)設(shè)置此參數(shù)為修改之前的值,CodeFirst才可以正確修改數(shù)據(jù)庫(kù)表;否則將視為【創(chuàng)建新表】
SelectFilter 查詢過(guò)濾SQL,實(shí)現(xiàn)類似 a.IsDeleted = 1 功能
DisableSyncStructure 禁用 CodeFirst 同步結(jié)構(gòu)遷移

3. 其他的還是看 https://github.com/2881099/FreeSql/blob/master/Docs/codefirst.md

Blog.cs

using FreeSql.DataAnnotations;
using System;

namespace Webapi.FreeSql.Domain
{
    public class Blog
    {
        [Column(IsIdentity = true, IsPrimary = true)]
        public int BlogId { get; set; }
        [Column(DbType = "varchar(50)")]
        public string Title { get; set; }
        [Column(DbType = "varchar(500)")]
        public string Content { get; set; }
        public DateTime CreateTime { get; set; }


    }
}

Post.cs


using FreeSql.DataAnnotations;
using System;

namespace Webapi.FreeSql.Domain
{
    public class Post
    {
        [Column(IsIdentity = true, IsPrimary = true)]
        public int PostId { get; set; }
        [Column(DbType = "varchar(50)")]
        public string ReplyContent { get; set; }
        public int BlogId { get; set; }
        public DateTime ReplyTime { get; set; }
        public Blog Blog { get; set; }
    }
}

Startup.cs

非全部代碼,這里注意點(diǎn):要先在mysql中創(chuàng)建數(shù)據(jù)庫(kù)FreeSql_Blog,否則一直提示主庫(kù)xxxxx,官網(wǎng)未找到相關(guān)描述。

這里初始化FreeSql,并使用單例模式,注入到默認(rèn)的依賴中,這樣在Controller中即可直接注入。

namespace Webapi.FreeSql
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Fsql = new FreeSqlBuilder()
                        .UseConnectionString(DataType.MySql, @"Data Source=127.0.0.1;Port=3306;User ID=root;Password=123456;Initial Catalog=FreeSql_Blog;Charset=utf8;SslMode=none;Max pool size=10")
                        .UseAutoSyncStructure(true)
                        .Build();
        }

        public IFreeSql Fsql { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IFreeSql>(Fsql);

        }
    }
}

BlogController

在controllers文件夾新建一個(gè)控制器BlogController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FreeSql;
using Microsoft.AspNetCore.Mvc;
using Webapi.FreeSql.Domain;

namespace Webapi.FreeSql.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BlogController : ControllerBase
    {
        // GET api/Blog

        IFreeSql _fsql;
        public BlogController(IFreeSql fsql)
        {
            _fsql = fsql;
        }

        [HttpGet]
        public ActionResult<IEnumerable<Blog>> Get()
        {
            List<Blog> blogs = _fsql.Select<Blog>().OrderByDescending(r => r.CreateTime).ToList();

            return blogs;
        }

        // GET api/blog/5
        [HttpGet("{id}")]
        public ActionResult<Blog> Get(int id)
        {
            return _fsql.Select<Blog>(id).ToOne();
        }


        // DELETE api/blog/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
            _fsql.Delete<Blog>(new { BlogId = id }).ExecuteAffrows();
        }
    }
}

重新運(yùn)行,打開地址 http://localhost:5001/api/blog 會(huì)發(fā)現(xiàn)數(shù)據(jù)庫(kù)中生成了表blog,這時(shí)候表post并沒(méi)有生成。所以我們判斷,只有在訪問(wèn)到實(shí)體類才檢查是否存在表結(jié)構(gòu),然后執(zhí)行相應(yīng)的處理。

手動(dòng)向blog表中加一些數(shù)據(jù),然后再次請(qǐng)求

自動(dòng)同步實(shí)體結(jié)構(gòu)【開發(fā)環(huán)境必備】

此功能默認(rèn)為開啟狀態(tài),發(fā)布正式環(huán)境后,請(qǐng)修改此設(shè)置

Fsql = new FreeSqlBuilder()
          .UseConnectionString(DataType.MySql, @"連接字符串")
          .UseAutoSyncStructure(true)
          .Build();
                      
//UseAutoSyncStructure(true/false)【開發(fā)環(huán)境必備】自動(dòng)同步實(shí)體結(jié)構(gòu)到數(shù)據(jù)庫(kù),程序運(yùn)行中檢查實(shí)體表是否存在,然后創(chuàng)建或修改

// 也可使用此方法指定是否自動(dòng)同步結(jié)構(gòu)。                  
Fsql.CodeFirst.IsAutoSyncStructure = true;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容