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

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

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

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

选择Web API

此时的目录结构:

添加实体层Entity

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

添加后的目录结构

BaseEntity:

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

Product:

using Entity.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text; namespace Entity.Table
{
/// <summary>
/// 商品类
/// </summary>
public class Product : BaseEntity<long>
{
/// <summary>
/// 名称
/// </summary>
[StringLength()]
[Required]
public string Name { get; set; } /// <summary>
/// 描述
/// </summary>
[StringLength()]
[Required]
public string Description { get; set; } /// <summary>
/// 类别
/// </summary>
[Range(, int.MaxValue)]
public int Category { get; set; } /// <summary>
/// 原价
/// </summary>
[Required]
public decimal Price { get; set; } /// <summary>
/// 现价
/// </summary>
public decimal Discount { get; set; }
}
}

添加数据层DAL:

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

添加引用:

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

Microsoft.EntityFrameworkCore.Tools(迁移支持)

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

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup> <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.0-rtm-10062" />
<!--迁移支持必备-->
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" PrivateAssets="All" />
</ItemGroup> <ItemGroup>
<!--迁移支持必备-->
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup> <ItemGroup>
<ProjectReference Include="..\Entity\Entity.csproj" />
</ItemGroup> </Project>

添加DbContext数据上下文

using Entity.Table;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace DAL
{
public class ProductContext : DbContext
{
//https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/complex-data-model
public ProductContext(DbContextOptions<ProductContext> options) : base(options)
{
//在此可对数据库连接字符串做加解密操作
} public DbSet<Product> Courses { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
}

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

添加Service服务层

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

添加引用:

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

 <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.UnitOfWork" Version="2.0.1" />
</ItemGroup> <ItemGroup>
<ProjectReference Include="..\DAL\DAL.csproj" />
<ProjectReference Include="..\Entity\Entity.csproj" />
</ItemGroup>

文件目录如下:

IProductService:

using System;
using System.Collections.Generic;
using System.Text; namespace Service.ProductService
{
public interface IProductService
{
string Test();
}
}

ProductService:

using Entity.Table;
using Microsoft.EntityFrameworkCore; namespace Service.ProductService
{
public class ProductService : IProductService
{
private readonly IUnitOfWork _unitOfWork;
public ProductService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
} public string Test()
{
var repo = _unitOfWork.GetRepository<Product>();
repo.Insert(new Product
{
Category = ,
Description = "此商品为澳洲代购,买不了吃亏买不了上当",
Discount = (decimal)899.21,
Price = (decimal)98.2,
Name = "澳洲袋鼠粉",
});
_unitOfWork.SaveChanges();//提交到数据库
var result = repo.GetFirstOrDefault()?.Description ?? string.Empty;
return result;
}
}
}

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

<ItemGroup>
<ProjectReference Include="..\DAL\DAL.csproj" />
<ProjectReference Include="..\Service\Service.csproj" />
</ItemGroup>

完整csproj如下:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup> <ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
</ItemGroup> <ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup> <ItemGroup>
<ProjectReference Include="..\DAL\DAL.csproj" />
<ProjectReference Include="..\Service\Service.csproj" />
</ItemGroup> </Project>

控制器中使用service

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Service.ProductService;
namespace ASP.Net_Core_API.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
private IProductService _productService; public ValuesController(IProductService productService)
{
_productService = productService;
}
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
var result = _productService.Test();
return new string[] { "value1", result };
}
}
}

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

完整文件如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using Entity.Table;
using DAL;
using Service.ProductService; namespace ASP.Net_Core_API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ProductContext>(options =>
options.UseMySql(Configuration.GetConnectionString("MySqlConnection")));//添加Mysql支持 services.AddUnitOfWork<ProductContext>();//添加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.
public void Configure(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"表示已成功更新数据库

完整操作如下

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

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

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

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

PM>update-database

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

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

运行程序

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

专案下载链接:Demo

github源码链接(持续更新):DotNetCore2.0

搭建连接MySql的三层架构的ASP.NetCore2.0的WebApi的更多相关文章

  1. paip.最好的脚本语言node js 环境搭建连接mysql

    paip.最好的脚本语言node js 环境搭建连接mysql #====下载node...走十一个exe..容易的.. 1 #0----Hello world   .js 2 #---------模 ...

  2. CodeFirst从零搭建ASP.NETCore2.0

    没时间介绍了,废话不说先上车 以下所有扯淡都是建立在.NETCore2.0环境已经搭建好 右键解决方案>新建项目> 选择Web>ASP.NETCoreWeb应用程序(.NET Cor ...

  3. MySQL的三层架构之一----连接层

    1.mysql的服务端可以分为三层,分别是连接层,SQL层,存储层. 2.架构图 3.连接层定义了通信server端与client协议:

  4. 搭建三层架构(ASP.NET MVC+EF)

    昨天面试的时候最后做了一道上机题,竟然跪了,跪就跪在没有搭好框架,连接数据库总是程序报错. 回来之后亲自搭了一下框架,弄好后放到博客上.下图就是搭建好后,整个框架的结构就是这样,下面对框架中的文件进行 ...

  5. IntelliJ IDEA 2017版 spring-boot使用Spring Data JPA搭建基础版的三层架构

    1.配置环境pom <?xml version="1.0" encoding="UTF-8"?> <project xmlns="h ...

  6. pycharm连接mysql是出现Connection to orm02@127.0.0.1 failed. [08001] Could not create connection to database server. Attempted reconnect 3 times. Giving up.

    下面这个问题反正我是遇到了,也是难为我好几天,于是我决定发一个教程出来给大家看看!希望能帮助你们 原因: 可能是数据库的版本与本机装的驱动不匹配导致的, 解决方案一: 在 url 后面街上一句 因为笔 ...

  7. ASP.NetCore2.0概览

      微软为了统一微软平台,造就了.netStandard,不管之前的Framework还是最新的.netCore都必须支持.netStandard标准来统一各个平台的开发api. 以下是之前的微软各个 ...

  8. asp.net core2.0 连接mysql和mssql

    转自:https://www.jianshu.com/p/15a557ac43d9 1.连接mysql 第一步,新建asp.net core项目   新建项目 本例程作简单演示两种数据库的连接,为简便 ...

  9. 关于三层架构与MVC的一些理解

    刚毕业的时候,参与了一个上位机的系统开发.上位机所使用的是.net Windows Form技术. 当时,和一个北理的姑娘在一个项目组里.因为她来公司时间比较长,而且经验比较丰富,所以,上位机的架构由 ...

随机推荐

  1. AT24C02使用详解

    ---恢复内容开始--- 这篇文章是写给一个学弟看的,关于IIC,关于24C02的单字节写入\读取..页写入和读取,,学弟总是害怕协议,,,我总是对人家说,本来就这样的,协议就是人家这样规定的,,,如 ...

  2. Java 中判断 JSONObject 对应的 VALUE 为空

    目前发现有两种包.两种不一样的json包. 第一种情况是: json包是json-lib包是net.sf.json 怎样判断JSONObject返回的是字符串null还是null值. 研究源码发现.J ...

  3. Linux环境变量配置的三个方法--/etc/profile,~/.bashrc,shell

    [环境配置的原因] 在windows系统下,很多软件的安装都需要设置环境变量,比如安装JAVA JDK.如果不安装环境变量,在非软件安装的目录下运行javac命令,将会报告"找不到文件&qu ...

  4. 解析java中volatile关键字

    在Java多线程编程中经常volatile,有时候这个关键字和synchronized 或者lock经常有人混淆,具体解析如下:  在多线程的环境中会存在成员变量可见性问题: java的每个线程都存在 ...

  5. 【Spring 核心】装配bean(二) JavaConfig装配

    前面介绍完了组件扫描和自动装配,这里再来看一下装配bean的另一种方式JavaConfig. 包路径: src/main/java com.bonc-|--config--|--CDPlayerCon ...

  6. Win7电脑桌面的Administrator图标没了怎么办

    Win7电脑桌面的Administrator图标没了怎么办.. win7电脑桌面的Administrator图标没了,怎么办?在桌面空白处右键选择个性化,进入个性化之后,左边栏选择“更改桌面图标”勾选 ...

  7. 阿里云服务器(Windows)如何下载文件

    背景:公司只有我一个技术,在我之前还有一个老技术,属于兼职状态,为了尽快熟悉公司网站及app项目情况,我联系了老技术,请他尽快将代码发给我,他说代码文件过大,问我能不能连上服务器下载.百度了很多,都不 ...

  8. 四种JavaScript隐式类型转换的总结

    一般存在四种情况,JavaScript会对变量的数据类型进行转换. 目录 * if中的条件会被自动转为Boolean类型 * 会被转为false的数据 * 会被转为true的数据 * 参与+运算都会被 ...

  9. 如何删除当前正在使用的SQLLite文件?

    从网上搜索一大堆,套路几乎相同,但自己就是不行,怎么也不行,为什么不行呢?不行的话别人肯定不来坑博友了呀.然后放了一会,去拿下午茶回来,再次来看,恍然大悟,What?这么简单. 一开始代码如下: he ...

  10. python自学1——接口测试

    尝试写了一个简单的接口测试,基于Python3.4,主要用到了Python读取excel以及requests库的知识,也算是对这段时间Python基础知识学习的一个巩固吧. 因为还没有学习到Pytho ...