目录
-
在控制器注入上下文
新建一个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的分享就到这里,有什么问题下方评论留言哦