学习ASP.NET Core(03)-数据层逻辑层与模型转换

上一篇我们使用Code First的方式完成了数据库的建立 ,本章我们来完善一下数据访问层和业务逻辑层部分的内容


一、IDAL与DAL

根据依赖倒置原则,细节应该依赖于抽象,我们我们要针对抽象,即面向接口进行编程,其好处是解耦和利于重构

1、IDAL实现

1.1、基类接口

这里添加一个CURD操作的基类接口,名为IBaseRepository,其余每个model都对应一个接口并继承该基类接口。在这之前IDAL层需要添加对Model层的引用。如下:

using System;
using System.Linq;
using System.Threading.Tasks;
using BlogSystem.Model;

namespace BlogSystem.IDAL
{
    /// 
    /// 基类接口
    /// 
    /// 
    public interface IBaseRepository where TEntity : BaseEntity
    {
        /// 
        /// 新增数据
        /// 
        /// 
        /// 
        /// 
        Task CreateAsync(TEntity entity, bool saved = true);

        /// 
        /// 根据Id删除数据
        /// 
        /// 
        /// 
        /// 
        Task RemoveAsync(Guid id, bool saved = true);

        /// 
        /// 根据model删除对数据
        /// 
        /// 
        /// 
        /// 
        Task RemoveAsync(TEntity entity, bool saved = true);

        /// 
        /// 修改数据
        /// 
        /// 
        /// 
        /// 
        Task EditAsync(TEntity entity, bool saved = true);

        /// 
        /// 通过Id查询数据
        /// 
        /// 
        /// 
        Task GetOneByIdAsync(Guid id);

        /// 
        /// 获取所有数据
        /// 
        /// 
        IQueryable GetAll();

        /// 
        /// 获取所有数据并排序
        /// 
        /// 
        IQueryable GetAllByOrder(bool asc = true);

        /// 
        /// 统一保存方法
        /// 
        /// 
        Task SavedAsync();

        /// 
        /// 判断对象是否存在
        /// 
        /// 
        /// 
        Task Exists(Guid id);
    }
}

1.2、其余接口

其余的每个model也都定义一个接口并继承IBaseRepository,给出一个示例,其余需要一一对应如下:

using BlogSystem.Model;

namespace BlogSystem.IDAL
{
    public interface IArticleRepository : IBaseRepository
{ } }

学习ASP.NET Core(03)-数据层逻辑层与模型转换_第1张图片


2、DAL实现

2.1、基类方法

首先DAL层需要添加对Model层和DAL层的引用,然后我们在DAL项目下添加一个名为BaseRepository的类,并继承基类接口IBaseRepository,添加泛型约束泛型参数为BlogSystem.Model中的BaseEntity,实现如下:

using System;
using System.Linq;
using System.Threading.Tasks;
using BlogSystem.IDAL;
using BlogSystem.Model;
using Microsoft.EntityFrameworkCore;

namespace BlogSystem.DAL
{
    /// 
    /// 实现基类接口
    /// 
    /// 
    public class BaseRepository : IBaseRepository where TEntity : BaseEntity, new()
    {
        private readonly BlogSystemContext _context;

        public BaseRepository(BlogSystemContext context)
        {
            _context = context;
        }

        /// 
        /// 新增数据
        /// 
        /// 
        /// 
        /// 
        public async Task CreateAsync(TEntity entity, bool saved = true)
        {
            _context.Set().Add(entity);
            if (saved) await _context.SaveChangesAsync();
        }

        /// 
        /// 根据Id删除数据
        /// 
        /// 
        /// 
        /// 
        public async Task RemoveAsync(Guid id, bool saved = true)
        {
            var t = new TEntity() { Id = id };
            _context.Entry(t).State = EntityState.Unchanged;
            t.IsRemoved = true;
            if (saved) await _context.SaveChangesAsync();
        }

        /// 
        /// 根据model删除数据
        /// 
        /// 
        /// 
        /// 
        public async Task RemoveAsync(TEntity model, bool saved = true)
        {
            await RemoveAsync(model.Id, saved);
        }

        /// 
        ///  修改数据
        /// 
        /// 
        /// 
        /// 
        public async Task EditAsync(TEntity entity, bool saved = true)
        {
            _context.Entry(entity).State = EntityState.Modified;

            //如果数据没有发生变化
            if (!_context.ChangeTracker.HasChanges()) return;

            if (saved) await _context.SaveChangesAsync();
        }

        /// 
        /// 通过Id查询数据
        /// 
        /// 
        /// 
        public async Task GetOneByIdAsync(Guid id)
        {
            return await GetAll().FirstOrDefaultAsync(m => m.Id == id);
        }

        /// 
        /// 获取所有数据
        /// 
        /// 
        public IQueryable GetAll()
        {
            return _context.Set().Where(m => !m.IsRemoved).AsNoTracking();
        }

        /// 
        /// 获取所有数据并排序
        /// 
        /// 
        public IQueryable GetAllByOrder(bool asc = true)
        {
            var data = GetAll();
            data = asc ? data.OrderBy(m => m.CreateTime) : data.OrderByDescending(m => m.CreateTime);
            return data;
        }

        /// 
        /// 统一保存方法
        /// 
        /// 
        public async Task SavedAsync()
        {
            await _context.SaveChangesAsync();
        }

        /// 
        /// 确认对象是否存在
        /// 
        /// 
        /// 
        public async Task Exists(Guid id)
        {
            return await GetAll().AnyAsync(m => m.Id == id);
        }
    }
}

2.2、其余方法

其余IDAL中的接口采用继承的方式实现,给出一个示例,其余同理,如下:

    public class ArticleCommentRepository : BaseRepository, IArticleCommentRepository
    {
        public ArticleCommentRepository() : base(new BlogSystemContext(new DbContextOptions()))
        {
        }
    }

学习ASP.NET Core(03)-数据层逻辑层与模型转换_第2张图片


二、模型对象

1、概念

在DAL层我们是对数据库的直接操作,面向的也是我们设计的包含属性的model;但在BLL层,面向的是业务逻辑,业务逻辑对应的是用户的操作,在软件的实际使用过程中,用户看到的页面并非对应一个完整的model,页面可能是model的一部分,也有可能由几个model的一部分组合而成的。为了解决这类问题,我们通常使用模型对象

2、常用的两种模型对象

1、Dto(Data Transfer Object):又名数据传输对象,常用来定义包含属性的实体类,它只引用基本数据类型,不引用对象类型,且没有行为,它只专注于数据本身,一般用于DAL和BLL之间的数据传输;

2、ViewModel:又名视图模型,它根据View创建,是View的数据容器,它专注的是View,用来呈现给用户,它由一个或多个Dto的组成;

3、实际应用

根据上面的描述,DAL与BLL层的数据交互我们应该使用Dto对象,呈现给页面时需要使用ViewModel对应,但在实际的开发中,Dto与ViewModel重合度很高,所以部分开发者只使用一种,但兼并两类角色。此外,Model与Dto/ViewModel之间的转换,我们可以使用EF的Select方法进行投影解决,或者使用AutoMapper之类的插件。

三、IBLL与ViewModel

这里我们根据功能大类,分为用户,文章、分类和评论,所以在IBLL中我们暂时先添加这4个接口, 在这之前需要添加对Model层的引用。根据实体对象部分的讲述,我们在Model层添加一个ViewModels文件夹,里面用来放置ViewModel对象,ViewModel对象属性通常会使用一些特性限制用户的录入。

1、基类接口

我们发现可以提取出常用的几个方法,避免重复代码,操作如下:

using BlogSystem.Model;
using System;
using System.Threading.Tasks;

namespace BlogSystem.IBLL
{
    /// 
    /// 基类服务接口
    /// 
    /// 
    public interface IBaseService where TEntity : BaseEntity
    {
        /// 
        /// 根据Id删除实体
        /// 
        /// 
        /// 
        Task RemoveAsync(Guid id);

        /// 
        /// 删除实体
        /// 
        /// 
        /// 
        Task RemoveAsync(TEntity entity);

        /// 
        /// 通过Id查询实体
        /// 
        /// 
        /// 
        Task GetOneByIdAsync(Guid id);

        /// 
        /// 判断实体是否存在
        /// 
        /// 
        /// 
        Task ExistsAsync(Guid id);
    }
}

2、文章接口与ViewModel

1、在Model层的ViewModel中添加相关的ViewModel,即用户所视内容需要用到的属性

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace BlogSystem.Model.ViewModels
{
    /// 
    /// 创建文章
    /// 
    public class CreateArticleViewModel
    {
        /// 
        /// 创建用户Id
        /// 
        public Guid UserId { get; set; }

        /// 
        /// 文章标题
        /// 
        [Required]
        public string Title { get; set; }

        /// 
        /// 文章内容
        /// 
        [Required]
        public string Content { get; set; }

        /// 
        /// 文章分类
        /// 
        public List CategoryIds { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace BlogSystem.Model.ViewModels
{
    /// 
    /// 编辑文章
    /// 
    public class EditArticleViewModel
    {
        /// 
        /// 文章Id
        /// 
        public Guid Id { get; set; }

        /// 
        /// 文章标题
        /// 
        [Required]
        public string Title { get; set; }

        /// 
        /// 文章内容
        /// 
        [Required]
        public string Content { get; set; }

        /// 
        /// 文章分类
        /// 
        public List CategoryIds { get; set; }
    }
}
using System;

namespace BlogSystem.Model.ViewModels
{
    /// 
    /// 文章列表
    /// 
    public class ArticleListViewModel
    {
        /// 
        /// 文章Id
        /// 
        public Guid ArticleId { get; set; }

        /// 
        /// 文章标题
        /// 
        public string Title { get; set; }

        /// 
        /// 文章内容
        /// 
        public string Content { get; set; }

        /// 
        /// 创建时间
        /// 
        public DateTime CreateTime { get; set; }

        /// 
        /// 账号
        /// 
        public string Account { get; set; }

        /// 
        /// 头像
        /// 
        public string ProfilePhoto { get; set; }
    }
}
using System;
using System.Collections.Generic;

namespace BlogSystem.Model.ViewModels
{
    /// 
    /// 文章详情
    /// 
    public class ArticleDetailsViewModel
    {
        /// 
        /// 文章Id
        /// 
        public Guid Id { get; set; }

        /// 
        /// 文章标题
        /// 
        public string Title { get; set; }

        /// 
        /// 文章内容
        /// 
        public string Content { get; set; }

        /// 
        /// 创建时间
        /// 
        public DateTime CreateTime { get; set; }

        /// 
        /// 作者
        /// 
        public string Account { get; set; }

        /// 
        /// 头像
        /// 
        public string ProfilePhoto { get; set; }

        /// 
        /// 分类Id
        /// 
        public List CategoryIds { get; set; }

        /// 
        /// 分类名称
        /// 
        public List CategoryNames { get; set; }

        /// 
        /// 看好人数
        /// 
        public int GoodCount { get; set; }
        /// 
        /// 不看好人数
        /// 
        public int BadCount { get; set; }

    }
}

2、接口实现:IArticleService继承基类接口,并添加如下方法:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BlogSystem.Model;
using BlogSystem.Model.ViewModels;

namespace BlogSystem.IBLL
{
    /// 
    /// 文章接口
    /// 
    public interface IArticleService : IBaseService
{ /// /// 新增文章 /// /// /// Task CreateArticleAsync(CreateArticleViewModel model); /// /// 编辑文章 /// /// /// Task EditArticleAsync(EditArticleViewModel model); /// /// 通过Id获取文章详情 /// /// /// Task GetArticleDetailsByArticleIdAsync(Guid articleId); /// /// 通过用户Id获取文章列表 /// /// /// Task> GetArticlesByUserIdAsync(Guid userId); /// /// 通过分类Id获取所有文章 /// /// /// Task> GetArticlesByCategoryIdAsync(Guid categoryId); /// /// 通过用户Id获取文章数量 /// /// /// Task GetArticleCountByUserIdAsync(Guid userid); /// /// 点赞文章 /// /// /// Task AddGoodCount(Guid articleId); /// /// 点灭文章 /// /// /// Task AddBadCount(Guid articleId); } }

3、分类接口与ViewModel

1、在Model层的ViewMode文件夹中添加相关的ViewModel

using System;
using System.ComponentModel.DataAnnotations;

namespace BlogSystem.Model.ViewModels
{
    public class CreateOrEditCategoryViewModel
    {
        /// 
        /// 分类名称
        /// 
        [Required]
        public string CategoryName { get; set; }

        /// 
        /// 创建用户Id
        /// 
        public Guid UserId { get; set; }
    }
}
namespace BlogSystem.Model.ViewModels
{
    public class CategoryListViewModel
    {
        /// 
        /// 分类名称
        /// 
        public string CategoryName { get; set; }
    }
}

2、分类接口:继承基类接口,并添加如下方法:

using BlogSystem.Model;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BlogSystem.Model.ViewModels;

namespace BlogSystem.IBLL
{
    /// 
    /// 分类服务接口
    /// 
    public interface ICategoryService : IBaseService
    {
        /// 
        /// 创建分类
        /// 
        /// 
        /// 
        Task CreateCategory(CreateOrEditCategoryViewModel model);

        /// 
        /// 编辑分类
        /// 
        /// 
        /// 
        Task EditCategory(CreateOrEditCategoryViewModel model);

        /// 
        /// 通过用户Id获取所有分类
        /// 
        /// 
        /// 
        Task> GetCategoryByUserIdAsync(Guid userId);
    }
}

4、用户接口与ViewModel

1、在Model层的ViewModel文件夹中添加相关的ViewModel

using System;
using System.ComponentModel.DataAnnotations;

namespace BlogSystem.Model.ViewModels
{
    /// 
    /// 用户注册
    /// 
    public class RegisterViewModel
    {
        /// 
        /// 账号
        /// 
        [Required]
        public string Account { get; set; }

        /// 
        /// 密码
        /// 
        [Required]
        public string Password { get; set; }

        /// 
        /// 确认密码
        /// 
        [Required]
        public string RequirePassword { get; set; }
    }
}
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace BlogSystem.Model.ViewModels
{
    /// 
    /// 用户登录
    /// 
    public class LoginViewModel
    {
        /// 
        /// 账号
        /// 
        [Required]
        public string Account { get; set; }

        /// 
        /// 密码
        /// 
        [Required]
        public string Password { get; set; }
    }
}

using System;
using System.ComponentModel.DataAnnotations;

namespace BlogSystem.Model.ViewModels
{
    /// 
    /// 修改用户密码
    /// 
    public class ChangePwdViewModel
    {
        /// 
        /// 用户Id
        /// 
        public Guid UserId { get; set; }

        /// 
        /// 旧密码
        /// 
        [Required]
        public string OldPassword { get; set; }

        /// 
        /// 新密码
        /// 
        [Required]
        public string NewPassword { get; set; }

        /// 
        /// 确认新密码
        /// 
        [Required]
        public string RequirePassword { get; set; }
    }
}
using System;
using System.ComponentModel.DataAnnotations;

namespace BlogSystem.Model.ViewModels
{
    /// 
    /// 修改用户头像
    /// 
    public class ChangeUserPhotoViewModel
    {
        /// 
        /// 用户Id
        /// 
        public Guid UserId { get; set; }

        /// 
        /// 用户头像
        /// 
        [Required]
        public string ProfilePhoto { get; set; }
    }
}
using System;

namespace BlogSystem.Model.ViewModels
{
    /// 
    /// 修改用户资料
    /// 
    public class ChangeUserInfoViewModel
    {
        /// 
        /// 用户Id
        /// 
        public Guid UserId { get; set; }

        /// 
        /// 账号
        /// 
        public string Account { get; set; }

        /// 
        /// 出生日期
        /// 
        public DateTime BirthOfDate { get; set; }

        /// 
        /// 性别
        /// 
        public Gender Gender { get; set; }
    }
}
using System;

namespace BlogSystem.Model.ViewModels
{
    /// 
    /// 用户详细信息-点击查看主页
    /// 
    public class UserDetailsViewModel
    {
        /// 
        /// 用户Id
        /// 
        public Guid UserId { get; set; }
        /// 
        /// 账号
        /// 
        public string Account { get; set; }
        /// 
        /// 头像
        /// 
        public string ProfilePhoto { get; set; }
        /// 
        /// 年龄
        /// 
        public int Age { get; set; }
        /// 
        /// 性别
        /// 
        public Gender Gender { get; set; }
        /// 
        /// 用户等级
        /// 
        public Level Level { get; set; }
        /// 
        /// 粉丝数
        /// 
        public int FansNum { get; set; }
        /// 
        /// 关注数
        /// 
        public int FocusNum { get; set; }
    }
}

2、用户接口:添加用户方法,如下:

using System;
using BlogSystem.Model;
using BlogSystem.Model.ViewModels;
using System.Threading.Tasks;

namespace BlogSystem.IBLL
{
    /// 
    /// 用户服务接口
    /// 
    public interface IUserService : IBaseService
    {
        /// 
        /// 注册
        /// 
        /// 
        /// 
        Task Register(RegisterViewModel model);

        /// 
        /// 登录成功返回userId
        /// 
        /// 
        /// 
        Task Login(LoginViewModel model);

        /// 
        /// 修改用户密码
        /// 
        /// 
        /// 
        Task ChangePassword(ChangePwdViewModel model);

        /// 
        /// 修改用户头像
        /// 
        /// 
        /// 
        Task ChangeUserPhoto(ChangeUserPhotoViewModel model);

        /// 
        /// 修改用户信息
        /// 
        /// 
        /// 
        Task ChangeUserInfo(ChangeUserInfoViewModel model);

        /// 
        /// 使用account获取用户信息
        /// 
        /// 
        /// 
        Task GetUserInfoByAccount(string account);
    }
}

5、评论接口与ViewModel

1、在Model层的ViewModel文件夹中添加相关的ViewModel

using System;

namespace BlogSystem.Model.ViewModels
{
    public class CommentListViewModel
    {
        /// 
        /// 文章Id
        /// 
        public Guid ArticleId { get; set; }

        /// 
        /// 用户Id
        /// 
        public Guid UserId { get; set; }

        /// 
        /// 账号
        /// 
        public string Account { get; set; }

        /// 
        /// 评论Id
        /// 
        public Guid CommentId { get; set; }

        /// 
        /// 评论内容
        /// 
        public string CommentContent { get; set; }

        /// 
        /// 创建时间
        /// 
        public DateTime CreateTime { get; set; }

    }
}

2、评论接口:添加接口方法,如下:

using BlogSystem.Model;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BlogSystem.Model.ViewModels;

namespace BlogSystem.IBLL
{
    /// 
    /// 评论服务接口
    /// 
    public interface ICommentService : IBaseService
    {
        /// 
        /// 添加评论
        /// 
        /// 
        /// 
        Task CreateComment(ArticleComment model);

        /// 
        /// 添加回复型评论
        /// 
        /// 
        /// 
        Task CreateReplyComment(CommentReply model);

        /// 
        /// 通过文章Id获取所有评论
        /// 
        /// 
        /// 
        Task> GetCommentsByArticleIdAsync(Guid articleId);
    }
}

我们这里暂时只是添加了目前考虑到的一些功能,后续以上的功能可能会进行相关的调整。

四、BLL实现

首先,我们需要对BLL层添加对Model,IDAL,IBLL的引用

1、基类方法

实现基类方法,如下:

using System;
using System.Threading.Tasks;
using BlogSystem.IBLL;
using BlogSystem.IDAL;
using BlogSystem.Model;

namespace BlogSystem.BLL
{
    /// 
    /// 基类方法
    /// 
    /// 
    public class BaseService : IBaseService where TEntity : BaseEntity, new()
    {
        //通过在子类的构造函数中注入,这里是基类,不用构造函数
        public IBaseRepository BaseRepository;

        /// 
        /// 根据Id删除对象
        /// 
        /// 
        /// 
        public async Task RemoveAsync(Guid id)
        {
            await BaseRepository.RemoveAsync(id);
        }

        /// 
        /// 根据实体删除对象
        /// 
        /// 
        /// 
        public async Task RemoveAsync(TEntity entity)
        {
            await BaseRepository.RemoveAsync(entity);
        }

        /// 
        /// 查询对象
        /// 
        /// 
        /// 
        public async Task GetOneByIdAsync(Guid id)
        {
            return await BaseRepository.GetOneByIdAsync(id);
        }

        /// 
        /// 判断对象是否存在
        /// 
        /// 
        /// 
        public async Task ExistsAsync(Guid id)
        {
            return await BaseRepository.Exists(id);
        }
    }
}

2、文章方法

文章方法实现如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BlogSystem.IBLL;
using BlogSystem.IDAL;
using BlogSystem.Model;
using BlogSystem.Model.ViewModels;
using Microsoft.EntityFrameworkCore;

namespace BlogSystem.BLL
{
    /// 
    /// 实现文章接口方法
    /// 
    public class ArticleService : BaseService
, IArticleService { private readonly IArticleRepository _articleRepository; private readonly IArticleInCategoryRepository _articleInCategoryRepository; private readonly ICategoryRepository _categoryRepository; //构造函数注入相关接口 public ArticleService(IArticleRepository articleRepository, IArticleInCategoryRepository articleInCategoryRepository, ICategoryRepository categoryRepository) { _articleRepository = articleRepository; BaseRepository = articleRepository; _articleInCategoryRepository = articleInCategoryRepository; _categoryRepository = categoryRepository; } /// /// 创建文章 /// /// /// public async Task CreateArticleAsync(CreateArticleViewModel model) { //新增文章 var article = new Article() { UserId = model.UserId, Title = model.Title, Content = model.Content }; await _articleRepository.CreateAsync(article); //新增文章所属分类 var articleId = article.Id; foreach (var categoryId in model.CategoryIds) { await _articleInCategoryRepository.CreateAsync(new ArticleInCategory() { ArticleId = articleId, CategoryId = categoryId }, false); } await _articleInCategoryRepository.SavedAsync(); } /// /// 编辑文章 /// /// /// public async Task EditArticleAsync(EditArticleViewModel model) { //保存文章更新 var article = await _articleRepository.GetOneByIdAsync(model.Id); article.Title = model.Title; article.Content = model.Content; await _articleRepository.EditAsync(article); //删除所属分类 var categoryIds = _articleInCategoryRepository.GetAll(); foreach (var categoryId in categoryIds) { await _articleInCategoryRepository.RemoveAsync(categoryId, false); } //添加所属分类 foreach (var categoryId in model.CategoryIds) { await _articleInCategoryRepository.CreateAsync(new ArticleInCategory() { ArticleId = model.Id, CategoryId = categoryId }, false); } //统一保存 await _articleInCategoryRepository.SavedAsync(); } /// /// 获取文章详情 /// /// /// public async Task GetArticleDetailsByArticleIdAsync(Guid articleId) { var data = await _articleRepository.GetAll().Include(m => m.User).Where(m => m.Id == articleId) .Select(m => new ArticleDetailsViewModel { Id = m.Id, Title = m.Title, Content = m.Content, CreateTime = m.CreateTime, Account = m.User.Account, ProfilePhoto = m.User.ProfilePhoto, GoodCount = m.GoodCount, BadCount = m.BadCount }).FirstAsync(); //处理分类 var categories = await _articleInCategoryRepository.GetAll().Include(m => m.Category) .Where(m => m.ArticleId == data.Id).ToListAsync(); data.CategoryIds = categories.Select(m => m.CategoryId).ToList(); data.CategoryNames = categories.Select(m => m.Category.CategoryName).ToList(); return data; } /// /// 根据用户Id获取文章列表信息 /// /// /// public async Task> GetArticlesByUserIdAsync(Guid userId) { var list = await _articleRepository.GetAllByOrder(false).Include(m => m.User).Where(m => m.UserId == userId) .Select(m => new ArticleListViewModel() { ArticleId = m.Id, Title = m.Title, Content = m.Content, CreateTime = m.CreateTime, Account = m.User.Account, ProfilePhoto = m.User.ProfilePhoto }).ToListAsync(); return list; } /// /// 通过分类Id获取文章列表 /// /// /// public async Task> GetArticlesByCategoryIdAsync(Guid categoryId) { var data = await _categoryRepository.GetOneByIdAsync(categoryId); var userId = data.UserId; return await GetArticlesByUserIdAsync(userId); } /// /// 获取用户文章数量 /// /// /// public async Task GetArticleCountByUserIdAsync(Guid userid) { return await _articleRepository.GetAll().CountAsync(m => m.UserId == userid); } /// /// 看好数量+1 /// /// /// public async Task AddGoodCount(Guid articleId) { var article = await _articleRepository.GetOneByIdAsync(articleId); article.GoodCount++; await _articleRepository.EditAsync(article); } /// /// 不看好数量+1 /// /// /// public async Task AddBadCount(Guid articleId) { var article = await _articleRepository.GetOneByIdAsync(articleId); article.BadCount--; await _articleRepository.EditAsync(article); } } }

3、分类方法

实现分类方法,如下:

using BlogSystem.IBLL;
using BlogSystem.IDAL;
using BlogSystem.Model;
using BlogSystem.Model.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlogSystem.BLL
{
    public class CategoryService : BaseService, ICategoryService
    {
        private readonly ICategoryRepository _categoryRepository;

        public CategoryService(ICategoryRepository categoryRepository)
        {
            _categoryRepository = categoryRepository;
            BaseRepository = categoryRepository;
        }

        /// 
        /// 创建分类
        /// 
        /// 
        /// 
        public async Task CreateCategory(CreateOrEditCategoryViewModel model)
        {
            await _categoryRepository.CreateAsync(new Category()
            {
                UserId = model.UserId,
                CategoryName = model.CategoryName
            });
        }

        /// 
        /// 编辑分类
        /// 
        /// 
        /// 
        public async Task EditCategory(CreateOrEditCategoryViewModel model)
        {
            await _categoryRepository.EditAsync(new Category()
            {
                UserId = model.UserId,
                CategoryName = model.CategoryName
            });
        }

        /// 
        ///  通过用户Id获取所有分类
        /// 
        /// 
        /// 
        public Task> GetCategoryByUserIdAsync(Guid userId)
        {
            return _categoryRepository.GetAll().Where(m => m.UserId == userId).Select(m => new CategoryListViewModel
            {
                CategoryName = m.CategoryName
            }).ToListAsync();
        }
    }
}

4、用户方法

实现用户方法,如下:

using BlogSystem.IBLL;
using BlogSystem.IDAL;
using BlogSystem.Model;
using BlogSystem.Model.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace BlogSystem.BLL
{
    public class UserService : BaseService, IUserService
    {
        private readonly IUserRepository _userRepository;

        public UserService(IUserRepository userRepository)
        {
            _userRepository = userRepository;
            BaseRepository = userRepository;
        }

        /// 
        /// 用户注册
        /// 
        /// 
        /// 
        public async Task Register(RegisterViewModel model)
        {
           //判断账户是否存在
            if (!await _userRepository.GetAll().AnyAsync(m => m.Account == model.Account))
            {
                await _userRepository.CreateAsync(new User()
                {
                    Account = model.Account,
                    Password = model.Password
                });
            }
        }

        /// 
        /// 用户登录
        /// 
        /// 
        /// 
        public async Task Login(LoginViewModel model)
        {
            var user = await _userRepository.GetAll().FirstOrDefaultAsync(m => m.Account == model.Account && m.Password == model.Password);
            return user != null ? user.Id : new Guid();
        }

        /// 
        /// 修改用户密码
        /// 
        /// 
        /// 
        public async Task ChangePassword(ChangePwdViewModel model)
        {
            if (await _userRepository.GetAll().AnyAsync(m => m.Id == model.UserId && m.Password == model.OldPassword))
            {
                var user = await _userRepository.GetAll().FirstOrDefaultAsync(m => m.Id == model.UserId && m.Password == model.OldPassword);
                user.Password = model.NewPassword;
                await _userRepository.EditAsync(user);
            }
        }

        /// 
        /// 修改用户照片
        /// 
        /// 
        /// 
        public async Task ChangeUserPhoto(ChangeUserPhotoViewModel model)
        {
            var user = await _userRepository.GetAll().FirstAsync(m => m.Id == model.UserId);
            user.ProfilePhoto = model.ProfilePhoto;
            await _userRepository.EditAsync(user);
        }

        /// 
        /// 修改用户信息
        /// 
        /// 
        /// 
        public async Task ChangeUserInfo(ChangeUserInfoViewModel model)
        {
            var user = await _userRepository.GetAll().FirstAsync(m => m.Id == model.UserId);
            user.Account = model.Account;
            user.Gender = model.Gender;
            user.BirthOfDate = model.BirthOfDate;
            await _userRepository.EditAsync(user);
        }

        /// 
        /// 通过账号名称获取用户信息
        /// 
        /// 
        /// 
        public async Task GetUserInfoByAccount(string account)
        {
            if (await _userRepository.GetAll().AnyAsync(m => m.Account == account))
            {
                return await _userRepository.GetAll().Where(m => m.Account == account).Select(m =>
                    new UserDetailsViewModel()
                    {
                        UserId = m.Id,
                        Account = m.Account,
                        ProfilePhoto = m.ProfilePhoto,
                        Age = DateTime.Now.Year - m.BirthOfDate.Year,
                        Gender = m.Gender,
                        Level = m.Level,
                        FansNum = m.FansNum,
                        FocusNum = m.FocusNum
                    }).FirstAsync();
            }
            return new UserDetailsViewModel();
        }
    }
}

5、评论方法

实现评论方法,如下:

using BlogSystem.IBLL;
using BlogSystem.IDAL;
using BlogSystem.Model;
using BlogSystem.Model.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlogSystem.BLL
{
    public class CommentService : BaseService, ICommentService
    {
        private readonly IArticleCommentRepository _commentRepository;
        private readonly ICommentReplyRepository _commentReplyRepository;

        public CommentService(IArticleCommentRepository commentRepository, ICommentReplyRepository commentReplyRepository)
        {
            _commentRepository = commentRepository;
            BaseRepository = commentRepository;
            _commentReplyRepository = commentReplyRepository;
        }

        /// 
        /// 添加评论
        /// 
        /// 
        /// 
        public async Task CreateComment(ArticleComment model)
        {
            await _commentRepository.CreateAsync(model);
        }

        /// 
        /// 添加回复型评论
        /// 
        /// 
        /// 
        public async Task CreateReplyComment(CommentReply model)
        {
            await _commentReplyRepository.CreateAsync(model);
        }

        /// 
        /// 根据文章Id获取评论信息
        /// 
        /// 
        /// 
        public async Task> GetCommentsByArticleIdAsync(Guid articleId)
        {
            return await _commentReplyRepository.GetAllByOrder(false).Where(m => m.ArticleId == articleId)
                .Include(m => m.ArticleComment).Include(m => m.User).Select(m => new CommentListViewModel()
                {
                    ArticleId = m.ArticleId,
                    UserId = m.UserId,
                    Account = m.User.Account,
                    CommentId = m.Id,
                    CommentContent = m.Content,
                    CreateTime = m.CreateTime
                })
                .ToListAsync();
        }
    }
}

本章只是从整体上将DAL层和BLL的进行了初步的完善,后续会进一步调整,完~

本人知识点有限,若文中有错误的地方请及时指正,方便大家更好的学习和交流。

本文的代码结构和方法参考了B站一位UP主的视频内容,地址如下:任生风影

原创文章声明

你可能感兴趣的:(学习ASP.NET Core(03)-数据层逻辑层与模型转换)