SycnSpBindService.cs 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using MySystem.SpModels;
  5. using Library;
  6. using LitJson;
  7. namespace MySystem
  8. {
  9. public class SycnSpBindService
  10. {
  11. public readonly static SycnSpBindService Instance = new SycnSpBindService();
  12. private SycnSpBindService()
  13. { }
  14. public void Start()
  15. {
  16. WebCMSEntities spdb = new WebCMSEntities();
  17. PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities();
  18. DateTime start = DateTime.Now.AddDays(-2);
  19. var Binds = spdb.BindRecord.Select(m => new { m.Id, m.CreateTime, m.Status, m.MerNo, m.MerSnNo }).Where(m => m.CreateTime >= start && m.Status == 1).OrderByDescending(m => m.Id).ToList();
  20. foreach (var Bind in Binds)
  21. {
  22. var tran = db.Database.BeginTransaction();
  23. try
  24. {
  25. PxcModels.MachineForSnNo posFor = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == Bind.MerSnNo) ?? new PxcModels.MachineForSnNo();
  26. PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == posFor.SnId);
  27. if (pos != null)
  28. {
  29. pos.BindingState = 1;
  30. pos.BindingTime = Bind.CreateTime;
  31. PxcModels.MachineForMerNo merFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == Bind.MerNo);
  32. if (merFor == null)
  33. {
  34. merFor = db.MachineForMerNo.Add(new PxcModels.MachineForMerNo()
  35. {
  36. MerNo = Bind.MerNo,
  37. SnId = pos.Id,
  38. }).Entity;
  39. }
  40. db.SaveChanges();
  41. RedisDbconn.Instance.Set("PosMachinesTwo", pos);
  42. BindRecord edit = spdb.BindRecord.FirstOrDefault(m => m.Id == Bind.Id);
  43. if (edit != null)
  44. {
  45. edit.Status = 2;
  46. spdb.SaveChanges();
  47. }
  48. string IdBrand = pos.UserId + "_" + pos.BrandId;
  49. PxcModels.UserMachineData MachineData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
  50. if (MachineData == null)
  51. {
  52. MachineData = db.UserMachineData.Add(new PxcModels.UserMachineData()
  53. {
  54. IdBrand = IdBrand,
  55. }).Entity;
  56. db.SaveChanges();
  57. }
  58. MachineData.BindCount += 1;
  59. MachineData.UnBindCount -= 1;
  60. db.SaveChanges();
  61. tran.Commit();
  62. RedisDbconn.Instance.Set("UserMachineData:" + IdBrand, MachineData);
  63. }
  64. }
  65. catch (Exception ex)
  66. {
  67. tran.Rollback();
  68. function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n" + Bind.Id, "同步SP绑定数据到MAIN异常");
  69. }
  70. tran.Dispose();
  71. }
  72. spdb.SaveChanges();
  73. spdb.Dispose();
  74. db.SaveChanges();
  75. db.Dispose();
  76. }
  77. }
  78. }