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

Posted johnyong

tags:

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

首先,创建数据库并创建数据表

测试数据表建表脚本

 1 USE [JobDb]
 2 GO
 3 
 4 /****** Object:  Table [dbo].[Account]    ******/
 5 SET ANSI_NULLS ON
 6 GO
 7 
 8 SET QUOTED_IDENTIFIER ON
 9 GO
10 
11 CREATE TABLE [dbo].[Account](
12     [Id] [uniqueidentifier] NOT NULL,
13     [Code] [nvarchar](50) NOT NULL,
14     [Name] [nvarchar](100) NULL,
15     [Password] [nvarchar](100) NULL,
16     [Status] [int] NULL,
17     [Created] [datetime] NULL,
18     [LastModified] [datetime] NULL,
19     [Version] [int] NULL,
20  CONSTRAINT [PK_Account] PRIMARY KEY CLUSTERED 
21 (
22     [Id] ASC
23 )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
24 ) ON [PRIMARY]
25 
26 GO

 

其次,创建数据库访问程序集

1、通过nuget引入Microsoft.EntityFrameworkCore.SqlServerMicrosoft.EntityFrameworkCore.Tools

技术图片

 

2、创建实体类

 1    ///<summary>
 2    /// 账号
 3    ///</summary> 
 4    public class Account
 5     {
 6         public Guid Id { get; set; }
 7         public string Code { get; set; }
 8         public string Name { get; set; }
 9         public string Password { get; set; }
10         public int Status { get; set; }
11         public DateTime Created { get; set; }
12         public DateTime LastModified { get; set; }
13         public int Version { get; set; }
14     }

 

3、创建ef数据库访问类

 1     /// <summary>
 2     /// JobDb数据库访问类
 3     /// </summary>
 4     public class JobSystemContainer : DbContext
 5     {
 6         public Account account;
 7 
 8         public DbSet<Account> Account { set; get; }
 9 
10         private string _ConnectionString { get; set; }
11         public JobSystemContainer()
12         {
13             //  Database.EnsureCreated();  //确保数据库已生成(存在)
14             _ConnectionString = ConfigSetting.GetConnectionString("JobSystemConnection");
15         }
16 
17         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
18         {
19             optionsBuilder.UseSqlServer(_ConnectionString);
20             base.OnConfiguring(optionsBuilder);
21         }
22 
23     }

 

4、配置数据连接

1 {
2   "ConnectionStrings": {
3     "JobSystemConnection": "Server=127.0.0.1;DataBase=JobDb;User Id=sa;password=123456",
4     "JobSystemConnection_ReadOnly": "Server=127.0.0.1;DataBase=JobDb;User Id=sa;password=123456"
5   },
6 
7   "AllowedHosts": "*"
8 }

附--配置文件读取类

   /// <summary>
    /// 配置设置
    /// </summary>
    public class ConfigSetting
    {
        private static IConfiguration root = new ConfigurationBuilder().SetBasePath(AppContext.BaseDirectory).AddJsonFile("appsettings.json").Build();
        /// <summary>
        /// 获取DB连接字符串
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetConnectionString(string name)
        {
            return root.GetConnectionString(name);
        } 
       
    }

 

最后、编写api,并进行测试

创建账号示例:

 1     [Route("api/[controller]")]
 2     [ApiController]
 3     public class JobAccountController : ControllerBase
 4     {
 5         /// <summary>
 6         /// 创建账号
 7         /// </summary>
 8         /// <param name="request"></param>
 9         /// <returns></returns>
10         [HttpPost("NewAccount")]
11         public ResponseDto<string> CreateAccount(CreateAccountDto request)
12         {
13             ResponseDto<string> result = new ResponseDto<string>()
14             {
15                 Code = ResultCode.FailureCode,
16             };
17             try
18             {
19                 using (var container = new JobEntity.JobSystemContainer())
20                 {
21                     Account acc = new Account()
22                     {
23                         Code = request.Code,
24                         Name = request.Name,
25                         Id = Guid.NewGuid(),
26                         Created = DateTime.Now,
27                         LastModified = DateTime.Now,
28                         Password = "123456",//初始密码,此处未加密
29                         Status = 1,
30                         Version = 1,
31                     };
32                     container.Account.Add(acc);
33                     container.SaveChanges();
34                     result.Code = ResultCode.SuccessCode;
35                     result.Message = "success";
36 
37                     return result;
38                 }
39             }
40             catch (Exception ex)
41             {
42                 //TODO记录日志,并提示返回
43                 result.Message = "Create fail:" + ex.Message;
44                 return result;
45             }
46         }
47     }

 

测试

技术图片

 

结果:

技术图片

 

技术图片

 

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

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

autoMapper dotnetcore webapi 自动添加映射 abp

EF Code-First 学习之旅

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

EF Code-First 学习之旅 DataAnnotations

DotNet Core 之旅