mysql 三层架构_搭建连接MySql的三层架构的ASP.NetCore2.0的WebApi

原标题:搭建连接MySql的三层架构的ASP.NetCore2.0的WebApi

原文链接:http://www.cnblogs.com/xiaoliangge/archive/2017/09/19/7543773.html

这里我们用三层架构搭建一个连接MySql的ASP.netCore模板的WebApi项目

首先添加WebApi项目(ASP.NetCore版本)

右键解决方案>新建项目>

选择Web>ASP.NET Core Web应用程序(.NET Core)

3a8a40f8b95259f23c98101ca9113af9.png

选择Web API

008f8210860268a14346b2b2aba52015.png

此时的目录结构:

2a9fefbfbbb8d922b9f05dc2d4959489.png

添加实体层Entity

右键添加>新建项目>.Net Core类库

83955146c85799636c9cd3a227227c20.png

添加后的目录结构

d4d01c0fb317d61127b0e2240f60c68a.png

BaseEntity:

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations;usingSystem.Runtime.Serialization;usingSystem.Text;namespaceEntity.Core{//DB表基础属性///publicabstractclassBaseEntity {publicBaseEntity() { CreteTime= DateTime.Now; }//主键Id///[DataMember] [Key]publicT Id { get; set; }//DB版号,Mysql详情参考;http://www.cnblogs.com/shanyou/p/6241612.html/[Timestamp]//Mysql不允许byte[]类型上标记TimeStamp/RowVersion,这里使用DateTime类型配合标记ConcurrencyCheck达到并发控制[ConcurrencyCheck]publicDateTime RowVersion { get; set; }//创建时间///publicDateTime CreteTime { get; set; } }}

Product:

usingEntity.Core;usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations;usingSystem.Text;namespaceEntity.Table{//商品类///publicclassProduct : BaseEntity {//名称///[StringLength( 20)] [Required]publicstringName { get; set; }//描述///[StringLength( 500)] [Required]publicstringDeion { get; set; }//类别///[Range( 1, int.MaxValue)]publicintCategory { get; set; }//原价///[Required]publicdecimalPrice { get; set; }//现价///publicdecimalDiscount { get; set; } }}

添加数据层DAL:

右键添加>新建项目>.NET Core 类库

40a1de362e99b6f1e6b7f33d1a4cbf0a.png

添加引用:

Microsoft.EntityFrameworkCore(也可加入Microsoft.AspNetCore.All,但会有用不到的功能造成浪费)

Microsoft.EntityFrameworkCore.Tools(迁移支持)

Pomelo.EntityFrameworkCore.MySql(Mysql支持)具体使用细则,请参考:Pomelo.EntityFrameworkCore.MySql使用细则

netcoreapp2.0

e5c2eb028bee81d85b11d7b2593676dc.png

添加DbContext数据上下文

usingEntity.Table;usingMicrosoft.EntityFrameworkCore;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceDAL{publicclassProductContext : DbContext {//https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/complex-data-modelpublicProductContext(DbContextOptions options) : base(options) {//在此可对数据库连接字符串做加解密操作}publicDbSet Courses { get; set; }protectedoverridevoidOnModelCreating(ModelBuilder modelBuilder) {base.OnModelCreating(modelBuilder); } }}

ASP.Net Core API项目中引用刚创建的DAL类库

添加Service服务层

右键添加>新建项目>.NetCore 类库

c6e8f34e9e8665e7f17e2a141a2709d5.png

添加引用:

添加Entity和DAL引用,其次再添加第三方数据仓储Microsoft.EntityFrameworkCore.UnitOfWork(最新)

文件目录如下:

2b8ef2a409179b54aa3a52d574079147.png

IProductService:

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceService.ProductService{publicinterfaceIProductService {stringTest(); }}

ProductService:

usingEntity.Table;usingMicrosoft.EntityFrameworkCore;namespaceService.ProductService{publicclassProductService : IProductService {privatereadonlyIUnitOfWork _unitOfWork;publicProductService(IUnitOfWork unitOfWork) { _unitOfWork= unitOfWork; }publicstringTest() {varrepo = _unitOfWork.GetRepository (); repo.Insert(newProduct { Category= 1, Deion= "此商品为澳洲代购,买不了吃亏买不了上当", Discount= ( decimal) 899.21, Price= ( decimal) 98.2, Name= "澳洲袋鼠粉", }); _unitOfWork.SaveChanges();//提交到数据库varresult = repo.GetFirstOrDefault()?.Deion ?? string.Empty;returnresult; } }}

ASP.Net Core API添加刚创建的Service类库引用

完整csproj如下:

netcoreapp2.0

控制器中使用service

using System.Collections.Generic;

usingMicrosoft.AspNetCore.Mvc;

usingService.ProductService; namespaceASP.Net_Core_API.Controllers{ [Route("api/[controller]")]publicclassValuesController : Controller {privateIProductService _productService;publicValuesController(IProductService productService) { _productService= productService; }//GET api/values[HttpGet]publicIEnumerable< string> Get() {varresult = _productService.Test();returnnewstring[] { "value1", result }; } }}

Startup文件中加入Mysql支持和对应的需要的注入的service还有UnitOfWork的支持

完整文件如下:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingMicrosoft.AspNetCore.Builder;usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.Extensions.Configuration;usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.Extensions.Logging;usingMicrosoft.Extensions.Options;usingMicrosoft.EntityFrameworkCore;usingEntity.Table;usingDAL;usingService.ProductService;namespaceASP.Net_Core_API{publicclassStartup {publicStartup(IConfiguration configuration) { Configuration= configuration; }publicIConfiguration Configuration { get; }//This method gets called by the runtime. Use this method to add services to the container.publicvoidConfigureServices(IServiceCollection services) { services.AddDbContext(options => options.UseMySql(Configuration.GetConnectionString("MySqlConnection")));//添加Mysql支持services.AddUnitOfWork ();//添加UnitOfWork支持services.AddScoped(typeof(IProductService), typeof(ProductService));//用ASP.NET Core自带依赖注入(DI)注入使用的类services.AddMvc(); }//This method gets called by the runtime. Use this method to configure the HTTP request pipeline.publicvoidConfigure(IApplicationBuilder app, IHostingEnvironment env) {if(env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); } }}

配置appsettings.json中Mysql连接字符串

{"ConnectionStrings": {"MySqlConnection": "Server=localhost;database=NetCore_WebAPI-Mysql;uid=root;pwd=111111;"},"Logging": {"IncludeScopes": false,"Debug": {"LogLevel": {"Default": "Warning"} },"Console": {"LogLevel": {"Default": "Warning"} } }}

迁移数据库:

打开程序包管理器控制台:工具>NuGet包管理器>程序包管理器控制台,默认项目选中包含了DbCOntext的程序集,这里是DAL,程序包源选择全部

输入:

PM>add-migration init

待执行后输出"To undo this action,use Remove-Migration"表示生成了迁移代码

然后再输入:

PM>update-database

待执行后输出"Done"表示已成功更新数据库

完整操作如下

f5f17bad2035d561477fa572e0fe5dd3.png

Tip:如果是非第一次迁移,就不能再输入PM>add-migration init,而是输入:

PM>add-migration "对本次迁移的说明"

例如,本次对Entity的某张表添加了Name属性.迁移时输入PM>add-migration AddName

输入以上待执行后,依旧输入以下即可

PM>update-database

会发现在DAL程序家下成功生成了以下目录

3f4d24240e611c83de36a6dffbbc9327.png

再打开数据库成功依据实体Entity生成了Product表

1e6b4de0f145914d6d57a6796324eace.png

运行程序

47164a7beebab5d4ae0a8ad337bbead0.png

成功Run通,奖励个鸡腿压压惊

专案下载链接:Demo(https://files.cnblogs.com/files/xiaoliangge/DotNetCore2.0.zip)

github源码链接:DotNetCore2.0(https://github.com/liuyl1992/DotNetCore2.0)返回搜狐,查看更多

责任编辑:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值