using System; using System.Collections.Generic; using System.Linq; using MySystem.SpModels; using Library; using LitJson; using System.Threading; namespace MySystem { public class SycnSpBindService { public readonly static SycnSpBindService Instance = new SycnSpBindService(); private SycnSpBindService() { } public void Start() { Thread th = new Thread(StartDo); th.IsBackground = true; th.Start(); } public void StartDo() { while (true) { try { WebCMSEntities spdb = new WebCMSEntities(); PxcModels.WebCMSEntities db = new PxcModels.WebCMSEntities(); DateTime start = DateTime.Now.AddDays(-5); 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(); foreach (var Bind in Binds) { var tran = db.Database.BeginTransaction(); try { PxcModels.MachineForSnNo posFor = db.MachineForSnNo.FirstOrDefault(m => m.SnNo == Bind.MerSnNo) ?? new PxcModels.MachineForSnNo(); PxcModels.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == posFor.SnId); if (pos != null) { pos.BindingState = 1; pos.BindingTime = Bind.CreateTime; PxcModels.MachineForMerNo merFor = db.MachineForMerNo.FirstOrDefault(m => m.MerNo == Bind.MerNo); if (merFor == null) { merFor = db.MachineForMerNo.Add(new PxcModels.MachineForMerNo() { MerNo = Bind.MerNo, SnId = pos.Id, }).Entity; } else { merFor.SnId = pos.Id; } db.SaveChanges(); RedisDbconn.Instance.Set("PosMachinesTwo", pos); BindRecord edit = spdb.BindRecord.FirstOrDefault(m => m.Id == Bind.Id); if (edit != null) { edit.Status = 2; spdb.SaveChanges(); } string IdBrand = pos.UserId + "_" + pos.BrandId; PxcModels.UserMachineData MachineData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand); if (MachineData == null) { MachineData = db.UserMachineData.Add(new PxcModels.UserMachineData() { IdBrand = IdBrand, }).Entity; db.SaveChanges(); } MachineData.BindCount += 1; MachineData.UnBindCount -= 1; db.SaveChanges(); tran.Commit(); RedisDbconn.Instance.Set("UserMachineData:" + IdBrand, MachineData); } } catch (Exception ex) { tran.Rollback(); function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n" + Bind.Id, "同步SP绑定数据到MAIN异常"); } tran.Dispose(); } spdb.SaveChanges(); spdb.Dispose(); db.SaveChanges(); db.Dispose(); } catch (Exception ex) { function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "同步SP绑定数据到MAIN异常"); } Thread.Sleep(1000); } } } }