.Net Core WebApi实现正删改查(CURD)

本文展示了如何在ASP.NET控制器中注入上下文并使用EFCore进行数据库操作,包括新增、查询、删除和修改学生信息。通过Student和DTO模型实现了数据的转换和验证,提供了自定义的返回结果类StudentResult。
摘要由CSDN通过智能技术生成

目录

在控制器注入上下文

代码实现

新增数据和返回数据用的模型

 控制器代码


  • 在控制器注入上下文

        新建一个Api控制器

        注入上下文

        private readonly MyDbContext _context;
        public StudentController(MyDbContext myDbContext)
        {
            _context = myDbContext;
        }

上下文的配置在我上一篇文章里,给你们链接可以看一下哦

EF Core配置DbContext 连接Mysql数据库_小涛668的博客-CSDN博客

  • 代码实现

  • 新增数据和返回数据用的模型

 public class Student
    {
        /// <summary>
        /// 主键
        /// </summary>
        public Guid Id { get; set; } = Guid.NewGuid();
        /// <summary>
        /// 姓名
        /// </summary>
        public string? Name { get; set; }
        /// <summary>
        /// 身高
        /// </summary>
        public string? Hight { get; set; }
        /// <summary>
        /// 年龄
        /// </summary>
        public int? Age { get; set; }
        /// <summary>
        /// 出生日期
        /// </summary>
        public DateTime? Birthday { get; set; }
        public DateTime CreateTime { get; set; } = DateTime.Now;
    }
    //新增用的dto
    public class StudentDto
    {
        /// <summary>
        /// 姓名
        /// </summary>
        public string? Name { get; set; }
        /// <summary>
        /// 身高
        /// </summary>
        public string? Hight { get; set; }
        /// <summary>
        /// 年龄
        /// </summary>
        public int? Age { get; set; }
        /// <summary>
        /// 出生日期
        /// </summary>
        public string? Birthday { get; set; }
    }
   //修改用的dto
    public class UpStudentDto
    {
        public Guid Id { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        public string? Name { get; set; }
        /// <summary>
        /// 身高
        /// </summary>
        public string? Hight { get; set; }
        /// <summary>
        /// 年龄
        /// </summary>
        public int? Age { get; set; }
        /// <summary>
        /// 出生日期
        /// </summary>
        public string? Birthday { get; set; }
    }
    //自己配的控制器返回数据
    public class StudentResult
    {
        /// <summary>
        /// 成功数量
        /// </summary>
        public int Count { get; set; }
        /// <summary>
        /// 数据
        /// </summary>
        public Student? Data { get; set; }
        /// <summary>
        /// 消息
        /// </summary>
        public string? Message { get; set; }
    }
  •  控制器代码

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost("AddStudent")]
        public async Task<ActionResult<StudentResult>> AddStudent(StudentDto dto)
        {
            try
            {

                if (string.IsNullOrWhiteSpace(dto.Name))
                {
                    return NotFound("姓名不能为空");
                }
                var IsExit = await _context.Students.Where(s => s.Name == dto.Name).FirstOrDefaultAsync();
                if (IsExit != null)
                {
                    return NotFound($"{dto.Name}:已经存在,请勿重复添加");
                }
                Student student = new Student()
                {
                    Name = dto.Name,
                    Hight = dto.Hight,
                    Age = dto.Age,
                    Birthday = Convert.ToDateTime(dto.Birthday)
                };
                _context.Students.Add(student);
                int i = await _context.SaveChangesAsync();
                StudentResult result = new StudentResult()
                {
                    Count = i,
                    Data = student,
                    Message = i > 0 ? "保存成功" : "保存失败"
                };
                if (i <= 0)
                {
                    return BadRequest(result);
                }
                return Ok(result);
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }

        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost("GetStudent")]
        public async Task<ActionResult<List<Student>>> GetStudent(StudentDto dto)
        {
            try
            {
                //*********************第一种查询********************///
                var data = (from student in _context.Students
                            select new Student
                            {
                                Id = student.Id,
                                Name = student.Name,
                                Hight = student.Hight,
                                Age = student.Age,
                                Birthday = student.Birthday,
                                CreateTime = student.CreateTime,
                            }).AsQueryable();
                if (!string.IsNullOrWhiteSpace(dto.Name))
                {
                    data = data.Where(s => s.Name.Contains(dto.Name));
                }
                if (!string.IsNullOrWhiteSpace(dto.Hight))
                {
                    data = data.Where(s => s.Hight.Contains(dto.Hight));
                }
                if (dto.Age != null && dto.Age != 0)
                {
                    data = data.Where(s => s.Age == dto.Age);
                }

                //结果:result1
                var result1 = await data.ToListAsync();
                //*********************第二种查询********************///
                var sql = "select * from students where 1=1";
                if (!string.IsNullOrWhiteSpace(dto.Name))
                {
                    sql += $" and `Name` LIKE '%{dto.Name}%'";
                }
                if (!string.IsNullOrWhiteSpace(dto.Hight))
                {
                    sql += $" and Hight= '{dto.Hight}'";
                }
                if (dto.Age != null && dto.Age != 0)
                {
                    sql += $" and Age= {dto.Name}";
                }
                var result2 = await _context.Students.FromSqlRaw(sql).ToListAsync();

                //result1和result2均为方法   都可以返回   只是两种表达的形式
                return Ok(result2);
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpDelete("DeleteStudent")]
        public async Task<ActionResult<StudentResult>> DeleteStudent(Guid? id)
        {
            try
            {
                var isExt = await _context.Students.FirstOrDefaultAsync(s => s.Id == id);
                if (isExt == null)
                {
                    return NotFound("用户不存在");
                }
                _context.Students.Remove(isExt);
                int i = await _context.SaveChangesAsync();
                StudentResult result = new StudentResult()
                {
                    Count = i,
                    Data = isExt,
                    Message = i > 0 ? "删除成功" : "删除失败"
                };
                //删除失败
                if (i < 0)
                {
                    return BadRequest(result);
                }
                //删除成功
                return Ok(result);
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }

        }
        /// <summary>
        /// 反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPut("FindStudent")]
        public async Task<ActionResult<Student>> FindStudent(Guid? id)
        {
            try
            {
                var isExt = await _context.Students.FirstOrDefaultAsync(s => s.Id == id);
                if (isExt == null)
                {
                    return NotFound("用户不存在");
                }
                return Ok(isExt);
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut("UpStudent")]
        public async Task<ActionResult<StudentResult>> UpStudent(UpStudentDto? dto)
        {
            try
            {
                Student student = new Student()
                {
                    Id=dto.Id,
                    Name = dto.Name,
                    Hight = dto.Hight,
                    Age = dto.Age,
                    Birthday = Convert.ToDateTime(dto.Birthday)
                };
                _context.Students.Update(student);
                int i = await _context.SaveChangesAsync();
                StudentResult result = new StudentResult()
                {
                    Count = i,
                    Data = student,
                    Message = i > 0 ? "保存成功" : "保存失败"
                };
                if (i <= 0)
                {
                    return BadRequest(result);
                }
                return Ok(result);
            }
            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
        }

好啦,关于CURD的分享就到这里,有什么问题下方评论留言哦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农小小涛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值