文章概述
主要在介紹FreeSql在ASP.NTE Core WebApi中如何使用的過程,完成一個最簡單的博客系統的后端接口。
FreeSql 簡介
國人寫的一個功能強大的ORM,FreeSql 支持 MySql/SqlServer/PostgreSQL/Oracle/Sqlite,特點:輕量級、可擴展、基于 .NET Standard 跨平臺。
參考
FreeSql github https://github.com/2881099/FreeSql
項目準備
- Mysql 5.6
- Visual Studio 2019或2017、Visual Studio code
- .NET Core 2.2+
- PowerShell
- 懂點mvc,該教程不會教你如何使用 ASP .NET Core MVC、RESTful
創建一個webapi 的項目,起名為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 會出現404
請打開這個地址 https://localhost:5001/api/values ,可看到如下內容。
["value1","value2"]
接下來我們來集成FreeSql,我們以最簡單的命令和說明,詳細內容去官網看具體內容
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
代碼優先,使用過EntityFramework的應該很清楚這一概念,我的理解就是:在分析數據庫表關系時,不通過在數據庫中設計表,而是直接在代碼中聲明對應的類,使用導航屬性代替外鍵關聯,通過數據表字段與C#中的類庫對應,從而自動生成數據表。
db first
數據庫優先:需求分析后,直接設計數據庫,通過數據庫中的表,直接生成代碼,類。
開始
分析需求
我們以code first 為示例,學習如何使用freesql,實現一個簡單的博客。將表內容分為博客表(Blog)和評論表(Post)
Blog 表
字段名 | 字段類型 | 說明 |
---|---|---|
BlogId | int | 博客id |
Title | varchar(50) | 博客標題 |
Content | varchar(500) | 博客內容 |
CreateTime | DateTime | 發布時間 |
Post 表
字段名 | 字段類型 | 說明 |
---|---|---|
PostId | int | 評論id |
ReplyContent | varchar(50) | 標題 |
BlogId | int | 博客id |
ReplyTime | DateTime | 回復時間 |
建一個Domain文件夾,用于存放數據庫表中對應的實體類。
關于
1. Column屬性介紹,大家可以看源碼,解析
1). 比如:Blog表中指定了Title為varchar(50),我們如何通過代碼指定了主鍵,唯一值,字形。
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 | 數據庫列名 |
OldName | 指定數據庫舊的列名,修改實體屬性命名時,同時設置此參數為修改之前的值,CodeFirst才可以正確修改數據庫字段;否則將視為【新增字段】 |
DbType | 數據庫類型,如: varchar(255) |
IsPrimary | 主鍵 |
IsIdentity | 自增標識 |
IsNullable | 是否可DBNull |
IsIgnore | 忽略此列,不遷移、不插入 |
IsVersion | 設置行鎖(樂觀鎖)版本號,每次更新累加版本號,若更新整個實體時會附帶當前的版本號判斷(修改失敗時拋出異常) |
DbDefautValue | 數據庫默認值 |
MapType | 類型映射,比如:可將 enum 屬性映射成 typeof(string) |
Uniques | 唯一鍵,在多個屬性指定相同的標識,代表聯合鍵;可使用逗號分割多個 UniqueKey 名。 |
2. Table 的使用:用于在類的上面指定這個表的屬性
[Table(Name = "t_blog")]
public class Blog {
//...
}
更多屬性介紹
字段 | 備注 |
---|---|
Name | 數據庫表名 |
OldName | 指定數據庫舊的表名,修改實體命名時,同時設置此參數為修改之前的值,CodeFirst才可以正確修改數據庫表;否則將視為【創建新表】 |
SelectFilter | 查詢過濾SQL,實現類似 a.IsDeleted = 1 功能 |
DisableSyncStructure | 禁用 CodeFirst 同步結構遷移 |
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
非全部代碼,這里注意點:要先在mysql中創建數據庫FreeSql_Blog,否則一直提示主庫xxxxx,官網未找到相關描述。
這里初始化FreeSql,并使用單例模式,注入到默認的依賴中,這樣在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();
}
}
}
重新運行,打開地址 http://localhost:5001/api/blog 會發現數據庫中生成了表blog,這時候表post并沒有生成。所以我們判斷,只有在訪問到實體類才檢查是否存在表結構,然后執行相應的處理。
手動向blog表中加一些數據,然后再次請求
- http://localhost:5001/api/blog, 可看到相應的數據。
- http://localhost:5001/api/blog/1 可得到單個數據。
自動同步實體結構【開發環境必備】
此功能默認為開啟狀態,發布正式環境后,請修改此設置
Fsql = new FreeSqlBuilder()
.UseConnectionString(DataType.MySql, @"連接字符串")
.UseAutoSyncStructure(true)
.Build();
//UseAutoSyncStructure(true/false)【開發環境必備】自動同步實體結構到數據庫,程序運行中檢查實體表是否存在,然后創建或修改
// 也可使用此方法指定是否自動同步結構。
Fsql.CodeFirst.IsAutoSyncStructure = true;