DeviceRepository.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using GCAS.Model;
  2. using Dapper;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. namespace GCAS.Code
  8. {
  9. public class DeviceRepository
  10. {
  11. public async Task<int> Insert(DeviceModel entity)
  12. {
  13. string exitSql = "Select count(1) from device where name=@Name";
  14. string insertSql = "INSERT INTO device (ip,name,port,time,code,tareweight)VALUES(@ip,@name,@port,NOW(),@Code,@TareWeight)";
  15. using (IDbConnection conn = DataBaseConfig.GetSqlConnection())
  16. {
  17. var count = await conn.QueryFirstAsync<int>(exitSql, new { entity.Name });
  18. if (count > 0)
  19. {
  20. return -1;
  21. }
  22. return await conn.ExecuteAsync(insertSql, entity);
  23. }
  24. }
  25. public List<DeviceModel> GetList()
  26. {
  27. string selectSql = "SELECT device.id,device.ip,device.name,device.port,device.time,device.code,device.tareweight FROM device order by id asc";
  28. using (IDbConnection conn = DataBaseConfig.GetSqlConnection())
  29. {
  30. return conn.Query<DeviceModel>(selectSql).ToList();
  31. }
  32. }
  33. public async Task<int> Delete(int id)
  34. {
  35. string deleteSql = "Delete from device where id=@Id";
  36. using (IDbConnection conn = DataBaseConfig.GetSqlConnection())
  37. {
  38. return await Task.Run(() => conn.ExecuteAsync(deleteSql, new { Id = id }));
  39. }
  40. }
  41. public async Task<int> Update(DeviceModel entity)
  42. {
  43. string exitSql = "Select count(1) from device where name=@Name and id<>@Id";
  44. string updateSql = "UPDATE device SET device.ip=@Ip,device.name=@Name,device.port=@Port,device.code=@Code,device.tareweight=@TareWeight WHERE id=@Id ";
  45. using (IDbConnection conn = DataBaseConfig.GetSqlConnection())
  46. {
  47. var count = await conn.QueryFirstAsync<int>(exitSql, entity);
  48. if (count > 0)
  49. {
  50. return -1;
  51. }
  52. return await conn.ExecuteAsync(updateSql, entity);
  53. }
  54. }
  55. }
  56. }