c# WebApi database connection (EF framework)

1.EF framework package:

Install the EF framework package:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design

2.Create database

data sheet

CREATE table base_user (
id int IDENTITY(1,1) PRIMARY KEY not null
,t_name VARCHAR(50) not null
,t_city VARCHAR(50) 
,t_money int
)

3. Use the framework package to connect to the database

Select the package manager console in the view of VS and enter the command: (Scaffold-DbContext -Force "Server=.;Database=…;uid=…;Password=…;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context WebApiContext ) (replace the value after the equal sign with your own database information value)
After the command is executed, the EF framework will automatically generate the entity class corresponding to the data table.

4.Data processing

[ApiController]
[Route("user")]
puliic class BaseUserController:ControllerBase{
    
    
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="account">包括:账号/手机号/邮箱</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        [HttpGet("login")]
        public WebApiResponse Login(string account, string pwd)
        {
    
    
            WebApiContext context = null;
            try
            {
    
    
                context = new WebApiContext();
                BaseUser user = context.BaseUsers.FirstOrDefault(x => (x.TCode == account || x.TPhone == account || x.TEmail == account) && x.TPwd == pwd);
                if(user == null)
                {
    
    
                    return WebApiResponse.Create(2, "账号或密码错误");
                }
                user.TPwd = null;
                string token = Guid.NewGuid().ToString().Replace("-", "");
                UserData.AddToken(token, user.Id);
                Dictionary<string, object> data = new Dictionary<string, object>()
                {
    
    
                    ["user"] = user,
                    ["token"] = token
                };
                return WebApiResponse.OK(data);
            }
            catch (Exception ex)
            {
    
    
                return WebApiResponse.Create(1, "服务器异常");
            }
        }
        [HttpGet("selectById")]
        public WebApiResponse SeleteById(string token, int id)
        {
    
    
            BaseUser user = UserData.GetUserById(id);
            if (user == null)
            {
    
    
                return WebApiResponse.Create(1, "未查询到数据");
            }
            return WebApiResponse.OK(user);
        }

        /// <summary>
        /// 修改(会有问题,容易产生数据库和缓存不一致的情况)
        /// </summary>
        /// <returns></returns>
        [HttpPost("edit1")]
        public WebApiResponse Edit1(string token, BaseUserEditDto dto)
        {
    
    
            //当修改的时候,先删除缓存数据,再修改数据库,再次删除缓存数据
            BaseUser user = UserData.GetUserById(dto.Id);
            if (user == null)
            {
    
    
                return WebApiResponse.Create(2, "数据不存在");
            }
            WebApiContext context = null;

            try
            {
    
    
                context = new WebApiContext();
                user.TName = dto.TName;
                user.TCity = dto.TCity;
                user.TStatus = dto.TStatus;
                user.TEmail = dto.TEmail;
                user.TPhone = dto.TPhone;
                context.BaseUsers.Update(user);
                context.SaveChanges();
            }
            catch (Exception)
            {
    
    
                return WebApiResponse.Create(1, "服务器异常");
            }
            finally
            {
    
    
                context?.Dispose();
            }
            return WebApiResponse.OK("修改成功");
        }

 /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        [HttpPost("edit")]
        public WebApiResponse Edit(string token, BaseUserEditDto dto)
        {
    
    
            //当修改的时候,先删除缓存数据,再修改数据库,再次删除缓存数据
            WebApiContext context = null;
            try
            {
    
    
                //先删除缓存数据
                UserData.RemoveUserById(dto.Id);
                context = new WebApiContext();
                //再修改数据库
                BaseUser user = context.BaseUsers.FirstOrDefault(x => x.Id == dto.Id);
                if (user == null)
                {
    
    
                    return WebApiResponse.Create(2, "数据不存在");
                }
                user.TName = dto.TName;
                user.TCity = dto.TCity;
                user.TStatus = dto.TStatus;
                user.TEmail = dto.TEmail;
                user.TPhone = dto.TPhone;
                context.BaseUsers.Update(user);
                context.SaveChanges();
                //再次删除缓存数据
                UserData.RemoveUserById(dto.Id);
            }
            catch (Exception)
            {
    
    
                return WebApiResponse.Create(1, "服务器异常");
            }
            finally
            {
    
    
                context?.Dispose();
            }
            return WebApiResponse.OK("修改成功");
        }

        [HttpDelete("delete")]
        public WebApiResponse Delete(string token, int id)
        {
    
    
            WebApiContext context = null;
            try
            {
    
    
                context = new WebApiContext();
                BaseUser user = context.BaseUsers.FirstOrDefault(x => x.Id == id);
                if (user == null)
                {
    
    
                    return WebApiResponse.Create(2, "数据不存在");
                }
                context.BaseUsers.Remove(user);
                context.SaveChanges();
                //从缓存中删除
                UserData.RemoveUserById(user.Id);
                return WebApiResponse.OK();
            }
            catch (Exception)
            {
    
    
                return WebApiResponse.Create(1, "服务器异常");
            }
            finally
            {
    
    
                context?.Dispose();
            }
        }
}

Guess you like

Origin blog.csdn.net/qq_57212959/article/details/131311980