如何快速创建行业标准的 .NET Core CRUD API

作者 : 慕源网 本文共6305个字,预计阅读时间需要16分钟 发布时间: 2021-10-20 共567人阅读

概述

实际上,设计基于 CRUD 的应用程序在所有产品中都是相似的。但是,我们仍然需要从头开始编写相同的代码。此外,对于 CRUD 应用程序,最可取的模式是 Repository 模式。但是,如果我们有一个应该遵循 SOLID 规则并且可以与所有与 CRUD 相关的产品一起使用的通用工具,那就太好了。在本文中,我们将使用通过 NuGet 包 RS2.Core 实现的相同存储库模式。

所以,在这篇文章中,我们将——

  • 创建业务逻辑
  • 创建一个 Web API 项目
  • 添加模型类和数据库上下文。
  • 注册依赖项

先决条件

  • Visual Studio 2017
  • .NET Core SDK >2.0
  • RS2.Core

创建业务逻辑

选择添加 -> 新建项目菜单选项。在“新建项目”对话框中,从左侧选择 .NET Core,然后在右侧选择 Class Library (.NET Core) 模板。

为您的项目命名,选择要创建项目的文件夹,然后单击“确定”。这将创建您的第一个 .NET Core 类库项目。我给我的项目命名为“BusinessLogic”。

右键单击解决方案并选择“管理解决方案的 NuGet 包”。

选择“浏览”选项卡并搜索 RS2.Core。

在右侧标记 BusinessLogic 项目,然后单击“安装”。在许可证设备上按“我接受”。

在BusinessLogic项目下分别添加Entities、Logics、Context三个不同的文件夹。

创建实体

实体应该从包含所需属性的核心库继承。例如 – ID 字段(通用类型)、IsActive。EntityBase 是主实体的基类,EntityTranBase 是事务实体的基类,它包含创建和更新属性。现在让我们创建 Category 和 Product 实体。

类别

  • 将解决方案资源管理器上的“Class1”重命名为“Category”。
  • 将其移动到“实体”文件夹。
  • 替换为下面的代码。
using System;  
using RS2.Core;  
namespace BusinessLogic {  
    public class Category: EntityBase < int > {  
        public string CategoryName {  
            get;  
            set;  
        }  
        public string ImageURL {  
            get;  
            set;  
        }  
    }  
} 

Product

  • 右键单击“实体”文件夹。
  • 选择添加 > 类。
  • 将类命名为 Product 选择“添加”。
  • 替换为下面的代码
using System;  
using System.Collections.Generic;  
using RS2.Core;  
namespace BusinessLogic {  
    public class Product: EntityBase < long > {  
        public string ProductName {  
            get;  
            set;  
        }  
        public decimal Price {  
            get;  
            set;  
        }  
        public int CategoryId {  
            get;  
            set;  
        }  
        public virtual Category Category {  
            get;  
            set;  
        }  
    }  
}  

创建数据库上下文

对于代码优先方法,我们只需创建一个上下文类并为每个实体创建 DbSet 对象。让我们为产品和类别实体创建它们。

  • 右键单击“上下文”文件夹
  • 选择添加 > 类。
  • 将类命名为 ShoppingContext,选择“添加”。
  • 替换为下面的代码。
using Microsoft.EntityFrameworkCore;  
namespace BusinessLogic {  
    public class ShoppingContext: DbContext {  
        public ShoppingContext(DbContextOptions < ShoppingContext > options): base(options) {  
            Database.EnsureCreated();  
        }  
        public DbSet < Category > Categories {  
            get;  
            set;  
        }  
        public DbSet < Product > Products {  
            get;  
            set;  
        }  
    }  
}  

创建业务逻辑类

使用 RS2.Core 库创建业务逻辑非常简单。我们需要为每个实体创建一个接口,并从 IRepositoryBase 继承接口用于 CRUD 所需实体或 IGetRepository 用于只读实体(例如:国家,此对象不需要添加或编辑屏幕)。现在,Business 类应该继承自 Core Library 的 RepositoryBase 类创建的接口和我们为实体创建的接口。让我们为 Product 和 Category 实体创建相同的内容。

类别库

  • 右键单击 Logics 文件夹。
  • 选择添加 > 类
  • 将类命名为 CategoryRepository
  • 选择“添加”
  • 替换为下面的代码。
using RS2.Core;  
namespace BusinessLogic {  
    public interface ICategoryRepository: IRepositoryBase < Category, int > {}  
    public class CategoryRepository: RepositoryBase < Category, int > , ICategoryRepository {  
        public CategoryRepository(IUnitOfWork unitOfWork): base(unitOfWork) {}  
    }  
}  

产品库

  • 右键单击 Logics 文件夹。
  • 选择添加 > 类。
  • 将该类命名为 ProductRepository。
  • 选择“添加”。
  • 替换为下面的代码。
using RS2.Core;  
using Microsoft.EntityFrameworkCore;  
namespace BusinessLogic {  
    public interface IProductRepository: IRepositoryBase < Product, long > {}  
    public class ProductRepository: RepositoryBase < Product, long > , IProductRepository {  
        public ProductRepository(IUnitOfWork unitOfWork): base(unitOfWork) {}  
        protected override IQueryable < Product > GetAllAsyncQuery(bool excludeDeleted = true) {  
            return Entity.Include(e => e.Category).Where(p => !excludeDeleted || p.IsActive);  
        }  
    }  
}  

创建 API

现在,让我们创建一个 Web API 项目并为类别和产品实体创建 ASPI。使用以下步骤添加一个新项目。
  • 右键单击解决方案。
  • 选择添加 > 新建项目。
  • 选择 Web > ASP.NET Core Web 应用程序。
  • 将项目命名为 API,选择 OK。
  • 现在,选择 API 模板并按 OK。
  • 右键解决。
  • 选择“管理解决方案的 NuGet 包”。
  • 选择已安装选项卡并选择 RS2.Core。
  • 在右侧窗口标记 Api 项目,然后单击安装。
  • 接受许可证以完成安装。

向 API 项目添加业务逻辑项目引用

为了在 API 项目中使用业务实体和逻辑,我们使用以下步骤将 BusinessLogic 项目引用添加到 API 项目。

  • 右键单击API项目的依赖项
  • 选择“添加引用”。
  • 选择左侧的项目选项卡。
  • 从列表中标记 BusinessLogic,然后按 OK。
现在,按照以下步骤为 Category 和 Product 创建 API 控制器。
Category Controller

  • 右键单击控制器文件夹。
  • 选择添加 > 控制器,选择 API 控制器 – 空模板。
  • 在“添加新项目”对话框中,将类命名为CategoriesController,选择添加。

让我们从业务逻辑中调用 CRUD 操作。下面的代码将解释如何从我们的 API 为 Category 实体调用业务逻辑。

using System.Collections.Generic;  
using System.Threading.Tasks;  
using Microsoft.AspNetCore.Mvc;  
using RS2.Core;  
using BusinessLogic;  
namespace Api.Controllers {  
    [Produces("application/json")]  
    [Route("api/[controller]")]  
    [ApiController]  
    public class CategoriesController: ControllerBase {  
        private ICategoryRepository _categoryRepository;  
        private IUnitOfWork _unitOfWork;  
        public CategoriesController(ICategoryRepository categoryRepository, IUnitOfWork unitOfWork) {  
            _categoryRepository = categoryRepository;  
            _unitOfWork = unitOfWork;  
        }  
        // GET: api/Categories
        [HttpGet]  
        public async Task < IEnumerable < Category >> Get() {  
            return await _categoryRepository.GetAllAsync();  
        }  
        // GET: api/Categories/5  
        [HttpGet("{id}")]  
        public async Task < Category > Get(int id) {  
            return await _categoryRepository.GetAsync(id);  
        }  
        // POST: api/Categories 
        [HttpPost]  
        public async Task Post([FromBody] Category category) {  
            await _categoryRepository.SaveAsync(category);  
            // Commit the changes.  
            await _unitOfWork.CommitAsync();  
        }  
        // DELETE: api/ApiWithActions/5  
        [HttpDelete("{id}")]  
        public async Task Delete(int id) {  
            await _categoryRepository.SoftDelete(id); // Set Deleted flag.  
            //await _categoryRepository.HardDelete(id); // Delete from DB  
            // Commit the changes.  
            await _unitOfWork.CommitAsync();  
        }  
    }  
}  

Products Controller

  • 右键单击控制器文件夹。
  • 选择添加 > 控制器,选择 API 控制器 – 空模板。
  • 在“添加新项目”对话框中,将该类命名为 ProductsController,选择添加。

下面的代码将解释如何从 Product 实体的业务逻辑调用 API 方法。

using System.Threading.Tasks;  
using Microsoft.AspNetCore.Mvc;  
using RS2.Core;  
using BusinessLogic;  
namespace Api.Controllers {  
    [Produces("application/json")]  
    [Route("api/[controller]")]  
    [ApiController]  
    public class ProductsController: ControllerBase {  
        private IProductRepository _productRepository;  
        private IUnitOfWork _unitOfWork;  
        public ProductsController(IProductRepository productRepository, IUnitOfWork unitOfWork) {  
            _productRepository = productRepository;  
            _unitOfWork = unitOfWork;  
        }  
        // GET: api/Products  
        [HttpGet]  
        public async Task < IEnumerable < Proeuct >> Get() {  
            return await _productRepository.GetAllAsync();  
        }  
        // GET: api/Products/5  
        [HttpGet("{id}")]  
        public async Task < Proeuct > Get(int id) {  
            return await _productRepository.GetAsync(id);  
        }  
        // POST: api/Products  
        [HttpPost]  
        public async Task Post([FromBody] Product product) {  
            await _productRepository.SaveAsync(product);  
            // Commit the changes.  
            await _unitOfWork.CommitAsync();  
        }  
        // DELETE: api/ApiWithActions/5  
        [HttpDelete("{id}")]  
        public async Task Delete(int id) {  
            await _productRepository.SoftDelete(id); // Set Deleted flag.  
            //await _productRepository.HardDelete(id); // Delete from DB  
            // Commit the changes.  
            await _unitOfWork.CommitAsync();  
        }  
    }  
}  

注册依赖项

现在,我们需要注册依赖项,即在上面的控制器代码中,我们只是注入了适当的接口并调用了方法。所以,我们正在配置对那个接口的依赖,说这个接口包含这个类的对象。例如,如果我们使用 IProductRepository,那应该保存 ProductRepository 类的对象。我们在 StartUp.cs 中注入了这些依赖项。下面的代码将解释如何在 StartUp.cs 中配置依赖项。

public void ConfigureServices(IServiceCollection services)   
{  
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
    services.AddDbContext < ShoppingContext > (options => options.UseSqlServer(Configuration.GetConnectionString("ShoppingConnection")));  
    services.AddScoped < DbContext, ShoppingContext > ();  
    services.AddScoped < IUnitOfWork, UnitOfWork > ();  
    services.AddScoped < ICategoryRepository, CategoryRepository > ();  
    services.AddScoped < IProductRepository, ProductRepository > ();  
}  

我们已经完成了 API 的创建。以下是调用 API 的示例。确保您已在 appsettings.json 文件中正确配置连接字符串。

  • https://localhost:8080/api/products/2
  • https://localhost:8080/api/categories

慕源网 » 如何快速创建行业标准的 .NET Core CRUD API

常见问题FAQ

程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!

发表评论

开通VIP 享更多特权,建议使用QQ登录