public bool InsertDevice(NodeLine device) { try { using (DB db = new DB()) { NodeLine node = (from o in db.DeviceSetups where o.Id == device.DeviceSetupId select new NodeLine { DeviceSetupId = o.Id, Client = o.LineSetup.DataCollectionNode.Client, AddressType = o.AddressType, DataType = o.DataType, DowntimeThreshold = o.LineSetup.DowntimeThreshold, UptimeThreshold = o.LineSetup.UptimeThreshold, IPAddress = o.IpAddress, Line = o.LineSetup.Line, TagType = o.TagType, TrackDowntime = o.TrackDowntime, TrackingType = o.TrackingType, TagName = o.TagName }).FirstOrDefault(); if (node != null)//Already exists { DeviceSetup setup = (from o in db.DeviceSetups where o.Id == node.DeviceSetupId select o).FirstOrDefault(); if (setup != null) { setup.IpAddress = device.IPAddress; setup.TagName = device.TagName; setup.TagType = device.TagType; setup.TrackDowntime = device.TrackDowntime; setup.TrackingType = device.TrackingType; setup.AddressType = device.AddressType; setup.DataType = device.DataType; setup.LineSetup.Line = device.Line; setup.LineSetup.DowntimeThreshold = device.DowntimeThreshold; setup.LineSetup.UptimeThreshold = device.UptimeThreshold; setup.LineSetup.DataCollectionNode.Client = device.Client; setup.LineSetup.DataCollectionNode.ServerName = device.ServerName; return db.SaveChanges() > 0; } } else { DeviceSetup setup = new DeviceSetup(); setup.IpAddress = device.IPAddress; setup.TagName = device.TagName; setup.TagType = device.TagType; setup.TrackDowntime = device.TrackDowntime; setup.TrackingType = device.TrackingType; setup.AddressType = device.AddressType; setup.DataType = device.DataType; DataCollectionNode dataNode = (from o in db.DataCollectionNodes where o.Client == device.Client select o).FirstOrDefault(); if (dataNode == null) { dataNode = new DataCollectionNode(); dataNode.Password = "******"; setup.LineSetup.DataCollectionNode = dataNode; } setup.LineSetup.DataCollectionNode.Client = device.Client; LineSetup lineSetup = (from o in db.LineSetups where o.DataCollectionNode.Id == dataNode.Id select o).FirstOrDefault(); if (lineSetup == null) { lineSetup = new LineSetup(); setup.LineSetup = lineSetup; } setup.LineSetup.Line = device.Line; setup.LineSetup.DowntimeThreshold = device.DowntimeThreshold; setup.LineSetup.UptimeThreshold = device.UptimeThreshold; db.AddToLineSetups(lineSetup); return db.SaveChanges() > 0; } } return false; } catch (Exception ex) { String fileName = this.Server.MapPath("~/App_Data/log.txt"); File.AppendAllText(fileName, ex.ToString()); throw ex; } }