4.使用RESTful、FreeSql構(gòu)建簡(jiǎn)單的博客系統(tǒng)-集成AutoMapper

文章概述

本文使用ASP .NET Core的WEB API,構(gòu)建一個(gè)RESTful風(fēng)格的接口,使用Freesql訪問(wèn)MySQL數(shù)據(jù)庫(kù),實(shí)現(xiàn)二個(gè)表的簡(jiǎn)單博客,并集成AutoMapper。

接上一篇

Dto作用

當(dāng)我們使用RESTful提供接口時(shí),比如創(chuàng)建一個(gè)博客,修改一下博客內(nèi)容時(shí),他們的參數(shù)是有區(qū)別的。良好的設(shè)計(jì)應(yīng)該是

創(chuàng)建一個(gè)博客

POST /api/blog
data:
{
  "title": "string",
  "content": "string"
}

修改一個(gè)博客內(nèi)容

PUT /api/blog
data:
{
  "blogId":"int",
  "title": "string",
  "content": "string"
}

但一個(gè)blog 實(shí)體如下

    public class Blog
    {
        [Column(IsIdentity = true, IsPrimary = true)]
        public int BlogId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public DateTime CreateTime { get; set; }
        public virtual List<Post> Posts { get; set; }
    }

如果我們以Blog作為controllers中的參數(shù)時(shí)

       // POST api/blog
        [HttpPost]
        public void Post([FromBody] Blog blog)
        {
            blog.CreateTime=DateTime.Now;
            _fsql.Insert<Blog>(blog).ExecuteAffrows();
        }

這時(shí)修改swagger顯示的默認(rèn)參數(shù)是

{
  "blogId": 0,
  "title": "string",
  "content": "string",
  "createTime": "2019-06-30T07:33:05.524Z",
  "posts": [
    {
      "postId": 0,
      "replyContent": "string",
      "blogId": 0,
      "replyTime": "2019-06-30T07:33:05.524Z"
    }
  ]
}

如果我們不傳遞createTime,會(huì)出現(xiàn)異常,應(yīng)該createTime是DateTime,不能為null,只有DateTime?才能為null,有?為可空類型。

所以我們應(yīng)該為POST方式傳遞過(guò)來(lái)時(shí),新建一個(gè)實(shí)體類,我們稱之為DTO(Data Transfer Object),即數(shù)據(jù)傳輸對(duì)象,因?yàn)閏reateTime即使傳遞,后端為他賦了值,前臺(tái)傳了也無(wú)效。有了DTO,這樣可讓前端清楚他們應(yīng)該傳遞的參數(shù),而不會(huì)出現(xiàn)沒(méi)有作用的參數(shù)。

在根目錄創(chuàng)建Models/Blogs文件夾,在Blogs文件夾中創(chuàng)建

CreateBlogDto.cs

namespace Webapi.FreeSql.Models.Blogs
{
    public class CreateBlogDto
    {
        public string Title { get; set; }
        public string Content { get; set; }

    }
}

UpdateBlogDto.cs

namespace Webapi.FreeSql.Models.Blogs
{
    public class UpdateBlogDto
    {
        public int BlogId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    }
}


有了Dto后,我們會(huì)發(fā)現(xiàn)了新的問(wèn)題,往數(shù)據(jù)庫(kù)插入時(shí),往往使用了一些ORM,他們只支持原本的實(shí)體類,如Blog,Post。但不支持CreateBlogDto、UpdateBlogDto,我們可以手動(dòng),將一個(gè)類的值,賦值給另一個(gè)類。

    CreateBlogDto createBlogDto = new CreateBlogDto()
    {
        Title = "我是title",
        Content = "我是content"
    };

    Blog newBlog=new Blog()
    {
        Title = createBlogDto.Title,
        Content = createBlogDto.Content
    };

現(xiàn)在只是非常簡(jiǎn)單的二個(gè)屬性,我們還能忍受,但如果是十個(gè)屬性、而且有著大量的類與類之間的轉(zhuǎn)換呢。這時(shí)修改AutoMapper就閃亮登場(chǎng)了。

AutoMapper

作用:A convention-based object-object mapper.

我們是在ASP .NET Core下使用AutoMapper 官網(wǎng)介紹,如何依賴注入中使用

Setup

先cd到dotnetcore-examples\WebAPI-FreeSql\Webapi.FreeSql目錄

PS > dotnet add package AutoMapper
PS > dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection --version 6.1.1

在StartUp.cs中的ConfigureServices配置如下

   public void ConfigureServices(IServiceCollection services)
    {
        // .... Ignore code before this
        
        //AddAutoMapper會(huì)去找繼承Profile的類,
        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

        // .... Ignore code after this
    }

Adding Profiles

AutoMapper/BlogProfile.cs

using AutoMapper;
using Webapi.FreeSql.Domain;
using Webapi.FreeSql.Models.Blogs;

namespace Webapi.FreeSql.AutoMapper
{
    public class BlogProfile : Profile
    {
        public BlogProfile() 
        {
            CreateMap<CreateBlogDto, Blog>();
            CreateMap<UpdateBlogDto, Blog>();
        }
    }
}

AutoMapper/BlogProfile.cs

using AutoMapper;
using Webapi.FreeSql.Domain;
using Webapi.FreeSql.Models.Blogs;

namespace Webapi.FreeSql.AutoMapper
{
    public class PostProfile : Profile
    {
        public PostProfile()
        {
            CreateMap<CreatePostDto,Post>();
        }
    }
}

Models/Posts/SearchPostDto.cs根據(jù)博客id,得到分頁(yè)的評(píng)論時(shí),集成分頁(yè)類

using Webapi.FreeSql.Web;

namespace Webapi.FreeSql.Models.Posts
{
    public class SearchPostDto:PageDto
    {
        public int BlogId { get; set; }
    }
}

Controlers/BlogController.cs文件中,注入IMapper,

using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using Webapi.FreeSql.Domain;
using Webapi.FreeSql.Models.Blogs;
using Webapi.FreeSql.Web;

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

        private readonly IFreeSql _fsql;
        private readonly IMapper _mapper;
        public BlogController(IFreeSql fsql, IMapper mapper)
        {
            _fsql = fsql;
            _mapper = mapper;
        }

        /// <summary>
        /// 博客列表頁(yè) 
        /// </summary>
        /// <param name="pageDto">分頁(yè)參數(shù)</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<PagedResultDto<Blog>> Get([FromQuery]PageDto pageDto)
        {
            List<Blog> blogs = _fsql.Select<Blog>().OrderByDescending(r => r.CreateTime).Page(pageDto.PageNumber, pageDto.PageSize).ToList();
            long count = _fsql.Select<Blog>().Count();
            return new PagedResultDto<Blog>(count, blogs);
        }

        // GET api/blog/5
        [HttpGet("{id}")]
        public ActionResult<Blog> Get(int id)
        {
            // eg.1 return _fsql.Select<Blog>().Where(a => a.Id == id).ToOne();
            // eg.2
            return _fsql.Select<Blog>(id).ToOne();
        }

        // POST api/blog
        [HttpPost]
        public void Post([FromBody] CreateBlogDto createBlogDto)
        {
            Blog blog = _mapper.Map<Blog>(createBlogDto);
            blog.CreateTime = DateTime.Now;
            _fsql.Insert<Blog>(blog).ExecuteAffrows();
        }

        // PUT api/blog
        [HttpPut]
        public void Put([FromBody] UpdateBlogDto updateBlogDto)
        {

            //eg.1 更新指定列
            //_fsql.Update<Blog>(updateBlogDto.BlogId).Set(a => new Blog()
            //{
            //    Title = updateBlogDto.Title,
            //    Content = updateBlogDto.Content
            //}).ExecuteAffrows();

            //eg.2將這個(gè)實(shí)體更新到數(shù)據(jù)庫(kù)中。當(dāng)更新時(shí),會(huì)把其他列的值,如CreateTime也更新掉。
            //使用IgnoreColumns可忽略某一些列。

            Blog blog = _mapper.Map<Blog>(updateBlogDto);
            _fsql.Update<Blog>().SetSource(blog).IgnoreColumns(r => r.CreateTime).ExecuteAffrows();
        }

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

Controlers/BlogController.cs文件中,注入IMapper,

using FreeSql;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Webapi.FreeSql.Domain;
using Webapi.FreeSql.Models.Posts;
using Webapi.FreeSql.Web;

namespace Webapi.FreeSql.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PostController : ControllerBase
    {
        // GET: api/Post
        private readonly IFreeSql _fsql;
        private readonly IMapper _mapper;
        public PostController(IFreeSql fsql, IMapper mapper)
        {
            _fsql = fsql;
            _mapper = mapper;
        }

        /// <summary>
        /// 根據(jù)博客id、分頁(yè)條件查詢?cè)u(píng)論信息
        /// </summary>
        /// <param name="searchPostDto"></param>
        /// <returns></returns>
        [HttpGet]
        public PagedResultDto<Post> Get(SearchPostDto searchPostDto)
        {
            ISelect<Post> selectPost = _fsql
                .Select<Post>()
                .Where(r => r.BlogId == searchPostDto.BlogId);

            List<Post> posts = selectPost.OrderByDescending(r => r.ReplyTime)
                .Page(searchPostDto.PageNumber, searchPostDto.PageSize)
                .ToList();

            long total = selectPost.Count();

            return new PagedResultDto<Post>(total, posts);
        }

        // GET: api/Post/5
        [HttpGet("{id}", Name = "Get")]
        public Post Get(int id)
        {
            return _fsql.Select<Post>().Where(a => a.PostId == id).ToOne();
        }

        // POST: api/Post
        [HttpPost]
        public void Post([FromBody] CreatePostDto createPostDto)
        {
            Post post = _mapper.Map<Post>(createPostDto);
            post.ReplyTime = DateTime.Now;
            _fsql.Insert(post).ExecuteAffrows();
        }


        // DELETE: api/Post/
        [HttpDelete("{id}")]
        public async Task DeleteAsync(int id)
        {
            await _fsql.Delete<Post>(new Post { PostId = id }).ExecuteAffrowsAsync();
        }
    }
}

參考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容