码迷,mamicode.com
首页 > 数据库 > 详细

ef.core Mysql

时间:2019-01-30 14:10:59      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:show   ges   pat   lex   startup   rtu   DDM   类别   ota   

  • 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

标签:show   ges   pat   lex   startup   rtu   DDM   类别   ota   

原文地址:https://www.cnblogs.com/Ken-Cai/p/10337595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!