1. 程式人生 > >ef.core Mysql

ef.core Mysql

system ogg under 澳洲 framework 描述 ext 依賴 ger

  • Entity層
技術分享圖片
 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel.DataAnnotations;
 4 using System.Runtime.Serialization;
 5 using System.Text;
 6 
 7 namespace Entity.Core
 8 {
 9     /// <summary>
10     /// DB表基礎屬性
11     /// </summary>
12     public
abstract class BaseEntity<T> 13 { 14 public BaseEntity() 15 { 16 CreteTime = DateTime.Now; 17 } 18 /// <summary> 19 /// 主鍵Id 20 /// </summary> 21 [DataMember] 22 [Key] 23 public T Id { get; set
; } 24 25 /// <summary> 26 /// DB版號,Mysql詳情參考;http://www.cnblogs.com/shanyou/p/6241612.html 27 /// </summary> 28 //[Timestamp]//Mysql不允許byte[]類型上標記TimeStamp/RowVersion,這裏使用DateTime類型配合標記ConcurrencyCheck達到並發控制 29 [ConcurrencyCheck] 30 public DateTime RowVersion { get
; set; } 31 32 /// <summary> 33 /// 創建時間 34 /// </summary> 35 public DateTime CreteTime { get; set; } 36 } 37 }
BaseEntity 技術分享圖片
 1 using Entity.Core;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.ComponentModel.DataAnnotations;
 5 using System.Text;
 6 
 7 namespace Entity.Table
 8 {
 9     /// <summary>
10     /// 商品類
11     /// </summary>
12     public class Product : BaseEntity<long>
13     {
14         /// <summary>
15         /// 名稱
16         /// </summary>
17         [StringLength(20)]
18         [Required]
19         public string Name { get; set; }
20 
21         /// <summary>
22         /// 描述
23         /// </summary>
24         [StringLength(500)]
25         [Required]
26         public string Description { get; set; }
27 
28         /// <summary>
29         /// 類別
30         /// </summary>
31         [Range(1, int.MaxValue)]
32         public int Category { get; set; }
33 
34         /// <summary>
35         /// 原價
36         /// </summary>
37         [Required]
38         public decimal Price { get; set; }
39 
40         /// <summary>
41         /// 現價
42         /// </summary>
43         public decimal Discount { get; set; }
44     }
45 }
Product
  • 在DAL層添加以下引用

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Tools

Microsoft.EntityFrameworkCore.Relational

MySql.Data.EntityFrameworkCore

技術分享圖片
 1 using Entity;
 2 using Entity.Table;
 3 using Microsoft.EntityFrameworkCore;
 4 using System;
 5 using System.Collections.Generic;
 6 using System.Linq;
 7 using System.Text;
 8 
 9 namespace DAL
10 {
11     public class ProductContext : DbContext
12     {
13         //https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/complex-data-model
14         public ProductContext(DbContextOptions<ProductContext> options) : base(options)
15         {
16             //在此可對數據庫連接字符串做加解密操作
17         }
18 
19         public DbSet<Person> Person { get; set; }
20         public DbSet<Product> Product { get; set; }
21 
22         protected override void OnModelCreating(ModelBuilder modelBuilder)
23         {
24             base.OnModelCreating(modelBuilder);
25         }
26     }
27 }
DbContext
  • Service 層

添加引用 Microsoft.EntityFrameworkCore.UnitOfWork

技術分享圖片
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace Service.ProductService
 6 {
 7     public interface IProductService
 8     {
 9         string Test();
10     }
11 }
IProductService 技術分享圖片
 1 using Entity.Table;
 2 using Microsoft.EntityFrameworkCore;
 3 
 4 namespace Service.ProductService
 5 {
 6     public class ProductService : IProductService
 7     {
 8         private readonly IUnitOfWork _unitOfWork;
 9         public ProductService(IUnitOfWork unitOfWork)
10         {
11             _unitOfWork = unitOfWork;
12         }
13 
14         public string Test()
15         {
16             var repo = _unitOfWork.GetRepository<Product>();
17             repo.Insert(new Product
18             {
19                 Category = 1,
20                 Description = "此商品為澳洲代購,買不了吃虧買不了上當",
21                 Discount = (decimal)899.21,
22                 Price = (decimal)98.2,
23                 Name = "澳洲袋鼠粉",
24             });
25             _unitOfWork.SaveChanges();//提交到數據庫
26             var result = repo.GetFirstOrDefault()?.Description ?? string.Empty;
27             return result;
28         }
29     }
30 }
ProductService
  • appsettings.json 的配置
{
  "ConnectionStrings": {
    "MySqlConnection": "Server=localhost;database=ProjectManager;uid=root;pwd=password;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}
  • Startup 的配置
        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().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

  • 有關數據庫遷移命令 (註意要選擇保護DbContext項目, 視圖 -> 其它窗口 -> 程序包管理器控制臺)

add-migration init (註: 初始化)

update-database

add-migration changeProductTable

remove-migration

如果出現找不到表 __efmigrationshistory, 則運行以下SQL

技術分享圖片
CREATE TABLE `__EFMigrationsHistory` (
  `MigrationId` varchar(95) NOT NULL,
  `ProductVersion` varchar(32) NOT NULL,
  PRIMARY KEY (`MigrationId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
創建 __EFMigrationsHistory 表

ef.core Mysql