Re0:在 .NetCore中 EF的基本使用
整理一下目前在用的EFCore
记得好像是因为懒得写sql,于是开始试着用EF
先根据数据库生成一个好东西,嗯
Scaffold-DbContext "Data Source=localhost;Initial Catalog=dbname;Persist Security Info=True;User ID=admin;Password=admin;Pooling=true;Max Pool Size=512; Min Pool Size=5;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
没有sql语句美滋滋
1 #region 添加 2 /// <summary> 3 /// Add 4 /// </summary> 5 /// <param name="obj"></param> 6 /// <returns></returns> 7 [HttpPost("Add")] 8 public IActionResult Add([FromBody] T obj) 9 { 10 try 11 { 12 _context.T.Add(obj); 13 var result = _context.SaveChanges().ToString(); 14 15 responseData.Status = 200; 16 responseData.Data = result; 17 responseData.Message = "Success"; 18 } 19 catch (Exception ex) 20 { 21 responseData.Status = 500; 22 responseData.Message = ex.Message; 23 return new JsonResult(responseData); 24 } 25 26 return new JsonResult(responseData); 27 } 28 #endregion
一时不用一时爽
1 #region 删除 2 //删除 3 [HttpDelete("Delete")] 4 public IActionResult Delete([FromBody] T obj) 5 { 6 try 7 { 8 var Test = new T { Id = obj.Id }; 9 _context.T.Remove(Test); 10 var result = _context.SaveChanges().ToString(); 11 12 responseData.Status = 200; 13 responseData.Data = result; 14 responseData.Message = "Success"; 15 } 16 catch (Exception ex) 17 { 18 responseData.Status = 500; 19 responseData.Message = ex.Message; 20 return new JsonResult(responseData); 21 } 22 23 return new JsonResult(responseData); 24 } 25 #endregion
一直不用一直爽
1 #region 修改 2 //修改 3 [HttpPut("Modify")] 4 public IActionResult Modify([FromBody] T obj) 5 { 6 try 7 { 8 int result = -1; 9 T t = _context.T.SingleOrDefault(u => u.Id == obj.Id); 10 11 if (t != null) 12 { 13 t = obj; 14 15 result = _context.SaveChanges(); 16 } 17 18 responseData.Status = 200; 19 responseData.Data = result; 20 responseData.Message = "Success"; 21 } 22 catch (Exception ex) 23 { 24 responseData.Status = 500; 25 responseData.Message = ex.Message; 26 return new JsonResult(responseData); 27 } 28 29 return new JsonResult(responseData); 30 } 31 #endregion
那么问题来了,想sql了怎么办?
能用Sql,但是不推荐;原因有机会了再补充
1 #region EFSql 2 //Select 3 [HttpGet("Query")] 4 public IActionResult Query() 5 { 6 try 7 { 8 string sql = "select * from bula bula bula"; 9 10 var result = _context.Set<Model>().FromSql(sql).ToList(); 11 12 if (result.Count() == 0) 13 { 14 responseData.Status = 201; 15 responseData.Message = "数据为空"; 16 17 return new JsonResult(responseData); 18 } 19 20 responseData.Status = 200; 21 responseData.Data = result; 22 responseData.Message = "Success"; 23 } 24 catch (Exception ex) 25 { 26 responseData.Status = 500; 27 responseData.Message = ex.Message; 28 return new JsonResult(responseData); 29 } 30 return new JsonResult(responseData); 31 } 32 #endregion