public static int UpdateChuyenTau(tblChuyenTau train, List <tblToaTau> listToaTau) { var db = Instance(); train.ModifiedDate = CommonFactory.GetCurrentDate(); var originChuyenTau = db.tblChuyenTaus.Include("tblToaTaus").Where(g => g.TrainID == train.TrainID).FirstOrDefault(); foreach (var toaTau in listToaTau) { //var originalToaTau = originChuyenTau.tblToaTaus // .Where(c => c.ToaTauID == toaTau.ToaTauID) // .FirstOrDefault(); var originalToaTau = db.tblToaTaus.Where(c => c.ToaTauID == toaTau.ToaTauID).FirstOrDefault(); if (originalToaTau != null) { toaTau.ModifiedDate = train.ModifiedDate; db.Detach(originalToaTau); if (originalToaTau.EntityState == EntityState.Detached) { object original = null; if (db.TryGetObjectByKey(originalToaTau.EntityKey, out original)) { db.ApplyPropertyChanges(originalToaTau.EntityKey.EntitySetName, toaTau); } } } else { originChuyenTau.tblToaTaus.Add(toaTau); } } foreach (var originalToaTau in originChuyenTau.tblToaTaus.Where(c => c.ToaTauID != 0).ToList()) { if (!listToaTau.Any(c => c.ToaTauID == originalToaTau.ToaTauID)) { //xoa lien ket cua toa tau cu voi BBBG List <tblHandoverResource> listHandoverResource = db.tblHandoverResources.Where(x => x.tblToaTau.ToaTauID == originalToaTau.ToaTauID).ToList(); foreach (tblHandoverResource obj in listHandoverResource) { db.DeleteObject(obj); } //xoa lien ket cua toa tau cu voi to khai List <tblToKhaiTauResource> listToKhaiTauResource = db.tblToKhaiTauResources.Where(x => x.tblToaTau.ToaTauID == originalToaTau.ToaTauID).ToList(); foreach (tblToKhaiTauResource obj in listToKhaiTauResource) { db.DeleteObject(obj); } //xoa toa tau db.DeleteObject(originalToaTau); } } db.Detach(originChuyenTau); if (originChuyenTau.EntityState == EntityState.Detached) { object original = null; if (db.TryGetObjectByKey(originChuyenTau.EntityKey, out original)) { db.ApplyPropertyChanges(originChuyenTau.EntityKey.EntitySetName, train); } } return(db.SaveChanges()); }