1. 程式人生 > >搭建連接MySql的三層架構的ASP.NetCore2.0的WebApi

搭建連接MySql的三層架構的ASP.NetCore2.0的WebApi

tof pri result conf see collect gin 允許 sset

裏我們用三層架構搭建一個連接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(20)]
        [Required]
        public string Name { get; set; }

        /// <summary>
        /// 描述
        /// </summary>
        [StringLength(500)]
        [Required]
        public string Description { get; set; }

        /// <summary>
        /// 類別
        /// </summary>
        [Range(1, 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="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" PrivateAssets="All" />
        <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.0-rtm-10062" />
    </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 = 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類庫引用

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

在 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<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")));

            services.AddUnitOfWork<ProductContext>();
            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"表示已成功更新數據庫

完整操作如下

技術分享

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

PM>add-migration "對本次遷移的說明"

例如,本次對Entity的某張表添加了Name屬性.遷移時輸入PM>add-migration AddName

輸入以上待執行後,依舊輸入以下即可

PM>update-database

會發現在DAL程序家下成功生成了以下目錄

技術分享

再打開數據庫成功依據實體Entity生成了Product表

技術分享

搭建連接MySql的三層架構的ASP.NetCore2.0的WebApi