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

该博客介绍了如何使用ASP.NET Core 2.0构建一个基于三层架构的WebApi项目,通过Entity Framework Core连接到MySQL数据库。步骤包括创建WebApi项目、定义实体、添加数据层(DAL)、实现数据库上下文、创建Service层以及在控制器中注入并使用Service。还涉及到数据库迁移和配置文件设置。
摘要由CSDN通过智能技术生成

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

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

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

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

6f775f769c177b8c5025976f1721d8df.png

选择Web API

ec35dd87eaf7799592a2141e2985fc02.png

此时的目录结构:

f1e4edf376166ee5f12df0f459d1a434.png

添加实体层Entity

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

b1e2394156b27694aed365676a05c6e7.png

添加后的目录结构

3e7acee74a9d804db88842eae61f1285.png

BaseEntity:

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Runtime.Serialization;

using System.Text;

namespace Entity.Core

{

///

/// DB表基础属性

///

public abstract class BaseEntity

{

public BaseEntity()

{

CreteTime = DateTime.Now;

}

///

/// 主键Id

///

[DataMember]

[Key]

public T Id { get; set; }

///

/// DB版号,Mysql详情参考;http://www.cnblogs.com/shanyou/p/6241612.html

///

//[Timestamp]//Mysql不允许byte[]类型上标记TimeStamp/RowVersion,这里使用DateTime类型配合标记ConcurrencyCheck达到并发控制

[ConcurrencyCheck]

public DateTime RowVersion { get; set; }

///

/// 创建时间

///

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

{

///

/// 商品类

///

public class Product : BaseEntity

{

///

/// 名称

///

[StringLength(20)]

[Required]

public string Name { get; set; }

///

/// 描述

///

[StringLength(500)]

[Required]

public string Description { get; set; }

///

/// 类别

///

[Range(1, int.MaxValue)]

public int Category { get; set; }

///

/// 原价

///

[Required]

public decimal Price { get; set; }

///

/// 现价

///

public decimal Discount { get; set; }

}

}

添加数据层DAL:

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

e2737275c28082353ac8a7bf0fccb8ab.png

添加引用:

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

Microsoft.EntityFrameworkCore.Tools(迁移支持)

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

netcoreapp2.0

c17c963b9158f602210c26c0cb05b348.png

添加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 options) : base(options)

{

//在此可对数据库连接字符串做加解密操作

}

public DbSet Courses { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

base.OnModelCreating(modelBuilder);

}

}

}

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

添加Service服务层

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

7e2d8c9f5d40672712e3ec5015eb6795.png

添加引用:

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

文件目录如下:

f5a7e98ecea98b247d95512698644fc0.png

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();

repo.Insert(new Product

{

Category = 1,

Description = "此商品为澳洲代购,买不了吃亏买不了上当",

Discount = (decimal)899.21,

Price = (decimal)98.2,

Name = "澳洲袋数粉",

});

_unitOfWork.SaveChanges();//提交到数据库

var result = repo.GetFirstOrDefault()?.Name ?? string.Empty;

return result;

}

}

}

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

在 ASP.Net Core API控制器中使用service数据库

向Controller注入需要使用的接口

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 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(options =>

options.UseMySql(Configuration.GetConnectionString("MySqlConnection")));

services.AddUnitOfWork();

services.AddScoped(typeof(IProductService), typeof(ProductService));

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"表示已成功更新数据库

完整操作如下

f0123cd5c600c6547c8a85199525e8f4.png

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

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

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

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

PM>update-database

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

ab7dfba4873d2cd2ca3691da68c68499.png

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

60ae515dbe61e8f8daaf0bdca2ed0b68.png

时间: 09-19

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值