DotnetCore之旅(4-1)---使用EF操作Mysql数据库

Posted johnyong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DotnetCore之旅(4-1)---使用EF操作Mysql数据库相关的知识,希望对你有一定的参考价值。

首先、创建数据库并创建对应的表

 1 CREATE TABLE `managementaccount` (
 2   `Id` char(36) NOT NULL COMMENT id,
 3   `Email` varchar(150) DEFAULT NULL COMMENT 邮箱,
 4   `Name` varchar(150) DEFAULT NULL COMMENT 名称,
 5   `Password` varchar(150) DEFAULT NULL COMMENT 密码,
 6   `Amount` decimal(10,0) DEFAULT NULL COMMENT 金额,
 7   `Created` datetime DEFAULT NULL COMMENT 创建时间,
 8   `LastModified` datetime DEFAULT NULL COMMENT 最近更新时间,
 9   PRIMARY KEY (`Id`)
10 )

 

第二步,创建数据访问程序集

1、创建成功后通过nuget引用MySql.Data.EntityFrameworkCoreMicrosoft.EntityFrameworkCore.Tools

技术图片

 

技术图片

2、配置数据库连接

1 {
2   "ConnectionStrings": {
3     "OrderSystemConnectionString": "Server=127.0.0.1;DataBase=OrderSystem;User Id=root;password=123456"  
4   },
5 
6   "AllowedHosts": "*"
7 }

 

3、创建实体以及数据库访问类

实体

 1    /// <summary>
 2     /// 
 3     /// </summary>
 4     public class ManagementAccount
 5     {
 6         /// <summary>
 7         /// 
 8         /// </summary>
 9         public string Id { get; set; }
10         /// <summary>
11         /// 
12         /// </summary>
13         public string Email { get; set; }
14         /// <summary>
15         /// 
16         /// </summary>
17         public string Name { get; set; }
18         /// <summary>
19         /// 
20         /// </summary>
21         public string Password { get; set; }
22         /// <summary>
23         /// 
24         /// </summary>
25         public decimal Amount { get; set; }
26         /// <summary>
27         /// 
28         /// </summary>
29         public DateTime Created { get; set; }
30         /// <summary>
31         /// 
32         /// </summary>
33         public DateTime LastModified { get; set; }
34     }

数据访问类:

   /// <summary>
    /// 訂單數據庫訪問類
    /// </summary>
    public class OrderSystemContainer : DbContext 
    {
        private string _ConnectionStringName = "OrderSystemConnectionString";
        public OrderSystemContainer()
        {
            //  Database.EnsureCreated();  //确保数据库已生成(存在) 
        }
        /// <summary>
        /// 配置
        /// </summary>
        /// <param name="optionsBuilder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string connectionString = ConfigSetting.GetConnectionString(_ConnectionStringName);
            optionsBuilder.Usemysql(connectionString);
            base.OnConfiguring(optionsBuilder);
        }

        #region Entity
        public virtual DbSet<ManagementAccount> ManagementAccount { get; set; }
        #endregion
    }

 

最后,创建api并进行测试

 

 1         /// <summary>
 2         /// 创建賬號
 3         /// </summary>
 4         [HttpPost("CreateManagementAccount")]
 5         public ResponseDto<string> CreateManagementAccount(CreateManagementAccountDto dto)
 6         {
 7             ResponseDto<string> response = new ResponseDto<string>()
 8             {
 9                 code = ResultFlagEnum.failure.ToString(),
10             };
11             try
12             {
13                 using (OrderSystemContainer context = new OrderSystemContainer())
14                 {
15                     context.ManagementAccount.Add(new ManagementAccount()
16                     {
17                         Id = Guid.NewGuid().ToString(),
18                         Amount = dto.amount,
19                         Created = DateTime.Now,
20                         LastModified = DateTime.Now,
21                         Email = dto.email,
22                         Name = dto.name,
23                         Password = Md5EncryptHelper.Md5Encrypt(dto.password),
24                     });
25                     context.SaveChanges();
26                     response.code = ResultFlagEnum.success.ToString();
27                     response.message = ResultFlagEnum.success.ToString();
28                     return response;
29                 }
30             }
31             catch (Exception ex)
32             {
33                 //TODO writeLog
34                 response.message = "异常:" + ex.Message;
35                 return response;
36             }
37         }

 

创建账号参数类

 1  /// <summary>
 2     /// 創建賬號入參
 3     /// </summary>
 4     public class CreateManagementAccountDto
 5     {
 6         /// <summary>
 7         /// 
 8         /// </summary>
 9         public string email { get; set; }
10         /// <summary>
11         /// 
12         /// </summary>
13         public string name { get; set; }
14         /// <summary>
15         /// 
16         /// </summary>
17         public string password { get; set; }
18         /// <summary>
19         /// 
20         /// </summary>
21         public decimal amount { get; set; }
22     }

 附,md5加密类

 1     public class Md5EncryptHelper
 2     {
 3         public static string Md5Encrypt(string text)
 4         {
 5             MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
 6             byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(text));
 7             StringBuilder sbResult = new StringBuilder();
 8             for (int i = 0; i < data.Length; i++)
 9             {
10                 sbResult.Append(data[i].ToString("x2"));
11             }
12             return sbResult.ToString();
13         }
14     }

 

以上是关于DotnetCore之旅(4-1)---使用EF操作Mysql数据库的主要内容,如果未能解决你的问题,请参考以下文章

DotnetCore之旅---swagger的简单使用

autoMapper dotnetcore webapi 自动添加映射 abp

EF Code-First 学习之旅

EF Code-First 学习之旅 数据库初始化

EF Code-First 学习之旅 DataAnnotations

DotNet Core 之旅