文章概述
主要在介紹FreeSql在ASP.NTE Core WebApi中如何使用的過程竿秆,完成一個最簡單的博客系統(tǒng)的后端接口规求。
FreeSql 簡介
國人寫的一個功能強(qiáng)大的ORM,FreeSql 支持 MySql/SqlServer/PostgreSQL/Oracle/Sqlite,特點(diǎn):輕量級佑女、可擴(kuò)展记靡、基于 .NET Standard 跨平臺谈竿。
參考
FreeSql github https://github.com/2881099/FreeSql
項(xiàng)目準(zhǔn)備
- Mysql 5.6
- Visual Studio 2019或2017、Visual Studio code
- .NET Core 2.2+
- PowerShell
- 懂點(diǎn)mvc摸吠,該教程不會教你如何使用 ASP .NET Core MVC空凸、RESTful
創(chuàng)建一個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 會出現(xiàn)404
請打開這個地址 https://localhost:5001/api/values 寸痢,可看到如下內(nèi)容呀洲。
["value1","value2"]
接下來我們來集成FreeSql,我們以最簡單的命令和說明啼止,詳細(xì)內(nèi)容去官網(wǎng)看具體內(nèi)容
- 官網(wǎng)文檔 http://freesql.net/doc
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)先献烦,使用過EntityFramework的應(yīng)該很清楚這一概念滓窍,我的理解就是:在分析數(shù)據(jù)庫表關(guān)系時,不通過在數(shù)據(jù)庫中設(shè)計(jì)表巩那,而是直接在代碼中聲明對應(yīng)的類吏夯,使用導(dǎo)航屬性代替外鍵關(guān)聯(lián),通過數(shù)據(jù)表字段與C#中的類庫對應(yīng)即横,從而自動生成數(shù)據(jù)表噪生。
db first
數(shù)據(jù)庫優(yōu)先:需求分析后,直接設(shè)計(jì)數(shù)據(jù)庫东囚,通過數(shù)據(jù)庫中的表跺嗽,直接生成代碼,類舔庶。
開始
分析需求
我們以code first 為示例抛蚁,學(xué)習(xí)如何使用freesql,實(shí)現(xiàn)一個簡單的博客惕橙。將表內(nèi)容分為博客表(Blog)和評論表(Post)
Blog 表
字段名 | 字段類型 | 說明 |
---|---|---|
BlogId | int | 博客id |
Title | varchar(50) | 博客標(biāo)題 |
Content | varchar(500) | 博客內(nèi)容 |
CreateTime | DateTime | 發(fā)布時間 |
Post 表
字段名 | 字段類型 | 說明 |
---|---|---|
PostId | int | 評論id |
ReplyContent | varchar(50) | 標(biāo)題 |
BlogId | int | 博客id |
ReplyTime | DateTime | 回復(fù)時間 |
建一個Domain文件夾,用于存放數(shù)據(jù)庫表中對應(yīng)的實(shí)體類。
關(guān)于
1. Column屬性介紹钉跷,大家可以看源碼弥鹦,解析
1). 比如:Blog表中指定了Title為varchar(50),我們?nèi)绾瓮ㄟ^代碼指定了主鍵,唯一值爷辙,字形彬坏。
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ù)庫列名 |
OldName | 指定數(shù)據(jù)庫舊的列名,修改實(shí)體屬性命名時膝晾,同時設(shè)置此參數(shù)為修改之前的值栓始,CodeFirst才可以正確修改數(shù)據(jù)庫字段;否則將視為【新增字段】 |
DbType | 數(shù)據(jù)庫類型血当,如: varchar(255) |
IsPrimary | 主鍵 |
IsIdentity | 自增標(biāo)識 |
IsNullable | 是否可DBNull |
IsIgnore | 忽略此列幻赚,不遷移禀忆、不插入 |
IsVersion | 設(shè)置行鎖(樂觀鎖)版本號,每次更新累加版本號落恼,若更新整個實(shí)體時會附帶當(dāng)前的版本號判斷(修改失敗時拋出異常) |
DbDefautValue | 數(shù)據(jù)庫默認(rèn)值 |
MapType | 類型映射箩退,比如:可將 enum 屬性映射成 typeof(string) |
Uniques | 唯一鍵,在多個屬性指定相同的標(biāo)識佳谦,代表聯(lián)合鍵戴涝;可使用逗號分割多個 UniqueKey 名。 |
2. Table 的使用:用于在類的上面指定這個表的屬性
[Table(Name = "t_blog")]
public class Blog {
//...
}
更多屬性介紹
字段 | 備注 |
---|---|
Name | 數(shù)據(jù)庫表名 |
OldName | 指定數(shù)據(jù)庫舊的表名钻蔑,修改實(shí)體命名時啥刻,同時設(shè)置此參數(shù)為修改之前的值,CodeFirst才可以正確修改數(shù)據(jù)庫表咪笑;否則將視為【創(chuàng)建新表】 |
SelectFilter | 查詢過濾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ù)庫FreeSql_Blog蒲肋,否則一直提示主庫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文件夾新建一個控制器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 會發(fā)現(xiàn)數(shù)據(jù)庫中生成了表blog剃法,這時候表post并沒有生成。所以我們判斷路鹰,只有在訪問到實(shí)體類才檢查是否存在表結(jié)構(gòu)贷洲,然后執(zhí)行相應(yīng)的處理。
手動向blog表中加一些數(shù)據(jù)晋柱,然后再次請求
- http://localhost:5001/api/blog优构, 可看到相應(yīng)的數(shù)據(jù)书劝。
- http://localhost:5001/api/blog/1 可得到單個數(shù)據(jù)墅拭。
自動同步實(shí)體結(jié)構(gòu)【開發(fā)環(huán)境必備】
此功能默認(rèn)為開啟狀態(tài),發(fā)布正式環(huán)境后宿亡,請修改此設(shè)置
Fsql = new FreeSqlBuilder()
.UseConnectionString(DataType.MySql, @"連接字符串")
.UseAutoSyncStructure(true)
.Build();
//UseAutoSyncStructure(true/false)【開發(fā)環(huán)境必備】自動同步實(shí)體結(jié)構(gòu)到數(shù)據(jù)庫碑诉,程序運(yùn)行中檢查實(shí)體表是否存在彪腔,然后創(chuàng)建或修改
// 也可使用此方法指定是否自動同步結(jié)構(gòu)。
Fsql.CodeFirst.IsAutoSyncStructure = true;