ef.core Mysql
- Entity层
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }
- 在DAL层添加以下引用
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Relational
Pomelo.EntityFrameworkCore.MySql
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }
- Service 层
添加引用 Microsoft.EntityFrameworkCore.UnitOfWork
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }
- 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支持 using Microsoft.EnityFrameworkCore 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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
CREATE TABLE `__EFMigrationsHistory` ( `MigrationId` varchar(95) NOT NULL, `ProductVersion` varchar(32) NOT NULL, PRIMARY KEY (`MigrationId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;