예제 #1
0
        /// <summary>
        /// Save contract (delete or add according to Deleted and New properties)
        /// </summary>
        /// <param action="UpdatingUserID">Id of user performing the update</param>
        /// <param action="AuditChanges">Audit changes of update</param>
        /// <returns>The ID of the contract saved, or 0 if contract was deleted, or -1 to indicate a failure to save contract</returns>
        public long Save(int UpdatingUserID, bool AuditChanges)
        {
            Logger.WriteGeneralVerbose("Contract class - save", "updating ContractActivity of {0}", this.ID);
            //Logger.Write(LogCategory.General, (this.New ? "Creating new " : (this.Deleted ? "Deleting " : "Updating ")) + "contract", "contract ID " + this.ID.ToString(), System.Diagnostics.TraceEventType.Information);
            DateTime updateDate = DateTime.Now;
            TopContractsV01Entities context = new TopContractsV01Entities(Utilities.getTestEnvName());
            TopContractsEntities.Contract efContract = null;
            if (this.New)
            {
                efContract = new TopContractsEntities.Contract();
                efContract.ContractUpdateDetail = new ContractUpdateDetail();
                //long ContractTypeContractsID = ConfigurationProvider.Default.ContractTypeContracts.ContractTypeContractsID;
                long ContractTypeContractsID = Utilities.contractTypeContractsID; // Code implemented by Viplav on 17 june 2013 for remove webconfig concept
                if (context.FieldGroups.Count(grp => grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToAll) > 0)
                    //foreach (FieldGroup grp in context.FieldGroups.Where(
                    //          grp => (grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToAll || grp.FieldGroupsContractTypesMAPs.Any(cTypeMap => cTypeMap.ContractType.ParentContractTypeID == ContractTypeContractsID) == true) && grp.Inactive == false)) //Viplav - 16-Oct-2012 // Implemented inactive condition for getting only active fieldsgroup
                    foreach (FieldGroup grp in context.FieldGroups.Where(
                              grp => (grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToAll && grp.Inactive == false)).ToList()) // Jan 31, 2013 - Need to be tested properly as now loop is running for VisibleToAll efFieldGroupsForContractInit
                    {
                        foreach (Field fld in grp.Fields.Where(grpf => grpf.Inactive == false)) //Viplav - 16-Oct-2012 // Implemented inactive condition for getting only active fields
                        {
                            if (fld.FieldType == (int)FieldTypes.EntityLink)
                            {
                                foreach (TopContractsEntities.ContractTypesFieldsToCreateDefault contDef in context.ContractTypesFieldsToCreateDefaults.Where(c => c.ContractTypeID == fld.LinkedEntityID))
                                {
                                    //efContract.ContractFields.Add(new TopContractsEntities.ContractField() { FieldGroupID = grp.EntryIdentifier, FieldID = contDef.FieldID, FieldValue = (contDef.Field.FieldType == (int)FieldTypes.ListSingle && contDef.Field.UseFirstAsDefault == true ? contDef.Field.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) });
                                    efContract.ContractFields.Add(new TopContractsEntities.ContractField() { OrganizationIdentifier = this.Properties.OrganizationIdentifier, FieldGroupID = grp.EntryIdentifier, FieldID = fld.FieldID, CatalogFieldID = contDef.FieldID, FieldValue = (contDef.Field.FieldType == (int)FieldTypes.ListSingle && contDef.Field.UseFirstAsDefault == true ? contDef.Field.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) });
                                }
                            }
                            else
                                efContract.ContractFields.Add(new TopContractsEntities.ContractField() { OrganizationIdentifier = this.Properties.OrganizationIdentifier, FieldGroupID = grp.EntryIdentifier, FieldID = fld.EntryIdentifier, FieldValue = (fld.FieldType == (int)FieldTypes.ListSingle && fld.UseFirstAsDefault == true ? fld.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) });
                        }
                    }
                if (context.FieldGroups.Count(grp => grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToTypes && grp.FieldGroupsContractTypesMAPs.Any(mp => mp.ContractTypeID == this.Properties.ContractTypeID)) > 0)
                    foreach (FieldGroup grp in context.FieldGroups.Where(grp => grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToTypes && grp.Inactive == false && grp.FieldGroupsContractTypesMAPs.Any(mp => mp.ContractTypeID == this.Properties.ContractTypeID)))//Viplav - 16-Oct-2012 // Implemented inactive condition for getting only active fieldsgroup
                        foreach (Field fld in grp.Fields.Where(grpf => grpf.Inactive == false)) //Viplav - 16-Oct-2012 // Implemented inactive condition for getting only active fields
                        {
                            if (fld.FieldType == (int)FieldTypes.EntityLink)
                            {
                                foreach (TopContractsEntities.ContractTypesFieldsToCreateDefault contDef in context.ContractTypesFieldsToCreateDefaults.Where(c => c.ContractTypeID == fld.LinkedEntityID))
                                {
                                    //efContract.ContractFields.Add(new TopContractsEntities.ContractField() { FieldGroupID = grp.EntryIdentifier, FieldID = contDef.FieldID, FieldValue = (contDef.Field.FieldType == (int)FieldTypes.ListSingle && contDef.Field.UseFirstAsDefault == true ? contDef.Field.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) });
                                    efContract.ContractFields.Add(new TopContractsEntities.ContractField() { OrganizationIdentifier = this.Properties.OrganizationIdentifier, FieldGroupID = grp.EntryIdentifier, FieldID = fld.FieldID, CatalogFieldID = contDef.FieldID, FieldValue = (contDef.Field.FieldType == (int)FieldTypes.ListSingle && contDef.Field.UseFirstAsDefault == true ? contDef.Field.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) });
                                }
                            }
                            else
                                efContract.ContractFields.Add(new TopContractsEntities.ContractField() { OrganizationIdentifier = this.Properties.OrganizationIdentifier, FieldGroupID = grp.EntryIdentifier, FieldID = fld.EntryIdentifier, FieldValue = (fld.FieldType == (int)FieldTypes.ListSingle && fld.UseFirstAsDefault == true ? fld.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) });
                        }
            }
            else
            {
                efContract = context.Contracts.Where(u => u.ContractID == this.ID).SingleOrDefault();
            }

            if (this.Deleted)
            {
                #region DELETING RELATED ENTITIES -----------------------------------------------------------------------------

                //For some unknown reason, eliminating the if-count>0 from before each of the foreach(s), throws an "object not set" exception even though alerts exist!
                context.ContractUpdateDetails.Remove(context.ContractUpdateDetails.Single(entry => entry.ContractID == this.ID));
                if (context.ContractApplications.Count(entry => entry.ContractID == this.ID) > 0)
                    foreach (TopContractsEntities.ContractApplication efContractApplication in context.ContractApplications.Where(entry => entry.ContractID == this.ID))
                        context.ContractApplications.Remove(efContractApplication);
                if (context.ContractActivities.Count(entry => entry.ContractID == this.ID) > 0)
                    foreach (TopContractsEntities.ContractActivity efContractActivity in context.ContractActivities.Where(entry => entry.ContractID == this.ID))
                    {
                        context.ContractActivities.Remove(efContractActivity);
                    }
                if (context.ContractDocs.Count(entry => entry.ContractID == this.ID) > 0)
                    foreach (TopContractsEntities.ContractDoc efContractDoc in context.ContractDocs.Where(entry => entry.ContractID == this.ID))
                        context.ContractDocs.Remove(efContractDoc);
                if (context.ContractGalleries.Count(entry => entry.ContractID == this.ID) > 0)
                    foreach (TopContractsEntities.ContractGallery efContractGallery in context.ContractGalleries.Where(entry => entry.ContractID == this.ID))
                    {
                        if (efContractGallery.ContractGalleryImages != null && efContractGallery.ContractGalleryImages.Count() > 0)
                        {
                            foreach (TopContractsEntities.ContractGalleryImage image in efContractGallery.ContractGalleryImages.ToList())
                            {
                                context.ContractGalleryImages.Remove(image);
                            }
                        }
                        context.ContractGalleries.Remove(efContractGallery);
                    }
                if (context.ContractFields.Count(entry => entry.ContractID == this.ID) > 0)
                    foreach (TopContractsEntities.ContractField efContractField in context.ContractFields.Where(entry => entry.ContractID == this.ID))
                        context.ContractFields.Remove(efContractField);
                if (context.ContractTodos.Count(entry => entry.ContractID == this.ID) > 0)
                {
                    foreach (TopContractsEntities.ContractTodo efContractTodo in context.ContractTodos.Where(entry => entry.ContractID == this.ID))
                    {
                        if (efContractTodo.ContractTodoRecipients != null)
                            for (int indx = efContractTodo.ContractTodoRecipients.Count - 1; indx >= 0; indx--)
                                context.ContractTodoRecipients.Remove(efContractTodo.ContractTodoRecipients.ElementAt(indx));
                        if (efContractTodo.ContractTodoUnits != null)
                            for (int indx = efContractTodo.ContractTodoUnits.Count - 1; indx >= 0; indx--)
                                context.ContractTodoUnits.Remove(efContractTodo.ContractTodoUnits.ElementAt(indx));
                        if (efContractTodo.DoneTodos != null)
                            for (int indx = efContractTodo.DoneTodos.Count - 1; indx >= 0; indx--)
                                context.DoneTodos.Remove(efContractTodo.DoneTodos.ElementAt(indx));
                        context.ContractTodos.Remove(efContractTodo);
                    }
                }
                foreach (TopContractsEntities.ContractUser efContractUser in context.ContractUsers.Where(entry => entry.ContractID == this.ID))
                    context.ContractUsers.Remove(efContractUser);

                #endregion
                context.Contracts.Remove(efContract);

            }
            if (this.New)
            {
                updateEfContract(ref efContract, ref context);
                context.Contracts.Add(efContract);
            }
            if (this.New == false & this.Deleted == false)
            {
                updateEfContract(ref efContract, ref context);
            }

            //Boaz-1 (8-Aug-2012) ------------------------------------------------------
            //All Todos which are linked to new events, should be made their "children" in the EF so that the foreign
            //key values will be  automatically generated when saving to the DB
            foreach (TopContractsEntities.ContractTodo todo in efContract.ContractTodos.Where(td => td.ActivityID < 0))
            {
                efContract.ContractActivities.SingleOrDefault(ca => ca.ActivityID == todo.ActivityID).ContractTodos.Add(todo);
            }

            // code to remove images from context for a deleted gallery
            foreach (ContractGallery gallery in this.ContractGalleries)
            {
                if (gallery.Deleted)
                {
                    foreach (TopContractsEntities.ContractGalleryImage galleryImage in context.ContractGalleryImages.Where(g => g.GalleryID == gallery.EntryId))
                        context.ContractGalleryImages.Remove(galleryImage);
                }

                // code to remove a deleted gallery image
                if (!gallery.New)
                {
                    foreach (ContractGalleryImage image in gallery.Images)
                    {
                        if (image.Deleted)
                        {
                            if (context.ContractGalleryImages.Any(g => g.GalleryImageID == image.EntryId))
                            {
                                TopContractsEntities.ContractGalleryImage galleryImage = context.ContractGalleryImages.SingleOrDefault(g => g.GalleryImageID == image.EntryId);
                                context.ContractGalleryImages.Remove(galleryImage);
                            }
                        }
                    }
                }
            }

            bool updateContractUpdateDetails = false;
            if (this.Deleted == false)
            {
                //If any of the entities related to the contract has changed, the Update-Date of the contract record itself should be updated...
                foreach (var entry in context.ChangeTracker.Entries())
                {
                    //Boaz 7-Aug-2012
                    //if (entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Modified && !(entry.Entity is EFContractRelatedEntryWithUpdate))
                    if (entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Modified || entry.State == System.Data.EntityState.Deleted)
                    {
                        updateContractUpdateDetails = true;
                    }
                }

                if (updateContractUpdateDetails)
                    foreach (var entry in context.ChangeTracker.Entries())
                    {
                        //Boaz 7-Aug-2012
                        //If any changed was made to a record in any table (entities related to the contract) which has
                        //UpdateDate and UpdateUserID fields, these fields are updated to reflect the change.
                        //These fields are NOT handled by the individual classes committing the changes to the
                        //database - they are handled centrally here to cut-down on the code
                        if (entry.Entity is EFContractRelatedEntryWithUpdate && entry.State != EntityState.Unchanged)
                        //if (entry.Entity is EFContractRelatedEntryWithUpdate)
                        {
                            ((EFContractRelatedEntryWithUpdate)entry.Entity).UpdatingDate = updateDate;
                            ((EFContractRelatedEntryWithUpdate)entry.Entity).UpdatingUserID = UpdatingUserID;
                        }
                        if (entry.Entity is TopContractsEntities.ContractDoc && entry.State == EntityState.Deleted)
                        {
                            TopContractsEntities.User Userdetail = context.Users.Where(usr => usr.UserID == UpdatingUserID).SingleOrDefault();
                            if (Userdetail != null)
                            {
                                if (context.Roles.Where(rol => rol.RoleID == Userdetail.DefaultRoleID).SingleOrDefault().DeleteDocs == false)
                                    entry.State = EntityState.Unchanged;
                            }
                        }
                        if (entry.Entity is TopContractsEntities.ContractActivity && entry.State == EntityState.Deleted)
                        {
                            TopContractsEntities.User Userdetail = context.Users.Where(usr => usr.UserID == UpdatingUserID).SingleOrDefault();
                            if (Userdetail != null)
                            {
                                if (context.Roles.Where(rol => rol.RoleID == Userdetail.DefaultRoleID).SingleOrDefault().DeleteActivities == false)
                                    entry.State = EntityState.Unchanged;
                                else  //********** Code Implemented for remove contract event with all associated Alerts,AlertsRecipiets & AlertsDone by Viplav on 20-Nov-2013**********************************
                                {
                                    List<TopContractsEntities.ContractTodo> contToDos = context.ContractTodos.Where(tod => tod.ActivityID == ((TopContractsEntities.ContractActivity)entry.Entity).ActivityID).ToList();
                                    foreach (TopContractsEntities.ContractTodo cntToDos in contToDos)
                                    {
                                        foreach (TopContractsEntities.ContractTodoRecipient cntToDosRec in context.ContractTodoRecipients.Where(tod => tod.TodoID == cntToDos.TodoID))
                                            context.ContractTodoRecipients.Remove(cntToDosRec);
                                        foreach (TopContractsEntities.DoneTodo doneToDos in context.DoneTodos.Where(todo => todo.OriginalTodoID == cntToDos.TodoID))
                                            context.DoneTodos.Remove(doneToDos);

                                        context.ContractTodos.Remove(cntToDos);
                                    }
                                }//*****************************************************************************************************************************************************************************
                            }
                        }
                    }
            }
            if (updateContractUpdateDetails)
            {
                efContract.ContractUpdateDetail.UpdateDate = updateDate;
                efContract.ContractUpdateDetail.UpdateUserID = UpdatingUserID;
            }
            //We want to keep tracking the changes after calling SaveChanges, for the purpose of auditing
            ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
            objectContext.DetectChanges();
            try
            {
                //Using SaveOptions.None to keep change-tracking... Requires objectContext.DetectChanges() before and objectContext.AcceptAllChanges() after...
                int rowsAffected = objectContext.SaveChanges(SaveOptions.None);
            }
            catch (System.Data.UpdateException updEx)
            {
                if (updEx.InnerException != null)
                    if (updEx.InnerException.Message.Contains("DELETE statement conflicted with the REFERENCE constraint") &&
                        updEx.InnerException.Message.Contains("FK_ContractTodos_ContractActivities"))
                    {
                        //    Logger.Write(updEx, System.Diagnostics.TraceEventType.Warning);
                        Logger.WriteGeneralWarning("Contract - Save()", "An attempt has been made to delete an Event With an Alert, in contract #{0}, by user #{1}", this.ID, UpdatingUserID);
                        throw new ExceptionDataContractSaveDeleteEventWithAlert();
                    }
                    else if (updEx.InnerException.Message.Contains("DELETE statement conflicted with the REFERENCE constraint") &&
                        updEx.InnerException.Message.Contains("FK_ContractFields_ContractActivities"))
                    {
                        Logger.WriteGeneralWarning("Contract - Save()", "An attempt has been made to delete an Event linked to an event type field, in contract #{0}, by user #{1}", this.ID, UpdatingUserID);
                        throw new ExceptionDataContractSaveDeleteEventWithEventTypeFields();
                    }
                    else if (updEx.InnerException.Message.Contains("FK_Contracts_Contracts") &&
                       updEx.InnerException.Message.Contains("ParentContractID"))
                    {
                        Logger.WriteGeneralWarning("Contract - Save()", "An attempt has been made to delete contract #{0}, by user #{1}, when this contract is a parenty of another contract", this.ID, UpdatingUserID);
                        throw new ExceptionDataContractDeleteDeleteContractWithChild();
                    }
                    else if (updEx.InnerException.Message.Contains("DELETE statement conflicted with the REFERENCE constraint") &&
                        updEx.InnerException.Message.Contains("FK_ContractFields_ContractDocs"))
                    {
                        Logger.WriteGeneralWarning("Contract - Save()", "Contract - Save()", "An attempt has been made to delete a document linked to a document-type field, in contract #{0}, by user #{1}", this.ID, UpdatingUserID);
                        throw new ExceptionDataContractSaveDeleteDocsWithDocumentTypeFields();
                    }
                    else
                    {
                        //  Logger.Write(updEx, System.Diagnostics.TraceEventType.Error);
                        Logger.WriteExceptionError("Contract - Save()", updEx, "The attempt to save contract #{0}, by user #{1}, has failed", this.ID, UpdatingUserID);
                        throw updEx;
                    }
            }

            //Boaz-1 (8-Aug-2012) -------------------------------------------------------
            //#region Setting the connection between new activities and their related new todos
            //if (this.Deleted == false)
            //{
            //    foreach (var newActivity in context.ChangeTracker.Entries())
            //    {
            //        if (newActivity.State == System.Data.EntityState.Added && newActivity.Entity is TopContractsEntities.ContractActivity)
            //        {
            //            foreach (var newTodo in context.ChangeTracker.Entries())
            //            {
            //                if (newTodo.State == System.Data.EntityState.Added && newTodo.Entity is TopContractsEntities.ContractTodo)
            //                {
            //                    if ((newTodo.Entity as TopContractsEntities.ContractTodo).ActivityID == (newActivity.Entity as TopContractsEntities.ContractActivity).ActivityID)
            //                    {
            //                        (newActivity.Entity as TopContractsEntities.ContractActivity).ContractTodos.Add((newTodo.Entity as TopContractsEntities.ContractTodo));
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}
            //#endregion

            //TopContractsEntities.ContractTodo todoToChange = null;

            if (AuditChanges)
            {
                HistManager histManager = new HistManager();
                int recordsWrittenToHistory = histManager.AuditChanges(updateDate, UpdatingUserID, this.New, this.Deleted, context.ChangeTracker.Entries().Where(e => e.State != System.Data.EntityState.Unchanged || e.Entity is TopContractsEntities.Contract));
            }

            objectContext.AcceptAllChanges();

            long contractIdSaved = -1; //will indicate failure, if no number is set
            foreach (var entry in context.ChangeTracker.Entries())
            {
                Logger.Write("entering the loop - for context.ChangeTracker.Entries()", System.Diagnostics.TraceEventType.Verbose);
                if (entry.Entity is TopContractsEntities.Contract)
                {
                    contractIdSaved = ((TopContractsEntities.Contract)entry.Entity).ContractID;
                }
                if (entry.Entity is TopContractsEntities.ContractDoc)
                {
                    TopContractsEntities.ContractDoc efDoc = entry.Entity as TopContractsEntities.ContractDoc;
                    TopContractsDAL10.ContractDoc doc = this.ContractDocs.SingleOrDefault(d => d.FileName == efDoc.FileName);
                    if (doc != null)
                    {
                        if (doc.New)
                        {
                            doc.EntryId = efDoc.DocumentID; //This is done especially for the process of file copying...
                        }
                    }
                }
                if (entry.Entity is TopContractsEntities.ContractGallery)
                {
                    TopContractsEntities.ContractGallery efGallery = entry.Entity as TopContractsEntities.ContractGallery;
                    foreach (TopContractsDAL10.ContractGallery gallery in this.ContractGalleries.Where(g => g.GalleryName == efGallery.GalleryName).ToList())
                    {
                        if (gallery.New)
                        {
                            gallery.EntryId = efGallery.GalleryID; //This is done especially for the process of file copying...
                        }
                    }
                }
            }

            if (this.Deleted)
                return 0;
            return contractIdSaved;
        }
예제 #2
0
        public long SaveEntityRecord(int UpdatingUserID, bool AuditChanges)
        {
            Logger.Write(LogCategory.General, (this.New ? "Creating new " : (this.Deleted ? "Deleting " : "Updating ")) + "contract", "contract ID " + this.ID.ToString(), System.Diagnostics.TraceEventType.Information);
            DateTime updateDate = DateTime.Now;
            TopContractsV01Entities context = new TopContractsV01Entities(Utilities.getTestEnvName());
            TopContractsEntities.Contract efContract = null;
            if (this.New)
            {
                efContract = new TopContractsEntities.Contract();
                efContract.ContractUpdateDetail = new ContractUpdateDetail();

                if (context.FieldGroups.Count(grp => grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToTypes && grp.FieldGroupsContractTypesMAPs.Any(mp => mp.ContractTypeID == this.Properties.ContractTypeID)) > 0)
                    foreach (FieldGroup grp in context.FieldGroups.Where(grp => grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToTypes && grp.Inactive == false && grp.FieldGroupsContractTypesMAPs.Any(mp => mp.ContractTypeID == this.Properties.ContractTypeID)))//Viplav - 16-Oct-2012 // Implemented inactive condition for getting only active fieldsgroup
                        foreach (Field fld in grp.Fields.Where(grpf => grpf.Inactive == false)) //Viplav - 16-Oct-2012 // Implemented inactive condition for getting only active fields
                        {
                            efContract.ContractFields.Add(new TopContractsEntities.ContractField() { OrganizationIdentifier = this.Properties.OrganizationIdentifier, FieldGroupID = grp.EntryIdentifier, FieldID = fld.EntryIdentifier, FieldValue = (fld.FieldType == (int)FieldTypes.ListSingle && fld.UseFirstAsDefault == true ? fld.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) });
                        }
            }
            else
            {
                efContract = context.Contracts.Where(u => u.ContractID == this.ID).SingleOrDefault();
            }

            if (this.Deleted)
            {
                #region DELETING RELATED ENTITIES -----------------------------------------------------------------------------

                //For some unknown reason, eliminating the if-count>0 from before each of the foreach(s), throws an "object not set" exception even though alerts exist!
                context.ContractUpdateDetails.Remove(context.ContractUpdateDetails.Single(entry => entry.ContractID == this.ID));

                if (context.ContractFields.Count(entry => entry.ContractID == this.ID) > 0)
                    foreach (TopContractsEntities.ContractField efContractField in context.ContractFields.Where(entry => entry.ContractID == this.ID))
                        context.ContractFields.Remove(efContractField);

                foreach (TopContractsEntities.ContractUser efContractUser in context.ContractUsers.Where(entry => entry.ContractID == this.ID))
                    context.ContractUsers.Remove(efContractUser);

                #endregion
                context.Contracts.Remove(efContract);

            }
            if (this.New)
            {
                updateEfContract(ref efContract, ref context);
                context.Contracts.Add(efContract);
            }
            if (this.New == false & this.Deleted == false)
            {
                updateEfContract(ref efContract, ref context);
            }

            //Boaz-1 (8-Aug-2012) ------------------------------------------------------
            //All Todos which are linked to new events, should be made their "children" in the EF so that the foreign
            //key values will be  automatically generated when saving to the DB
            foreach (TopContractsEntities.ContractTodo todo in efContract.ContractTodos.Where(td => td.ActivityID < 0))
            {
                efContract.ContractActivities.SingleOrDefault(ca => ca.ActivityID == todo.ActivityID).ContractTodos.Add(todo);
            }

            bool updateContractUpdateDetails = false;
            if (this.Deleted == false)
            {
                //If any of the entities related to the contract has changed, the Update-Date of the contract record itself should be updated...
                foreach (var entry in context.ChangeTracker.Entries())
                {
                    //Boaz 7-Aug-2012
                    //if (entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Modified && !(entry.Entity is EFContractRelatedEntryWithUpdate))
                    if (entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Modified || entry.State == System.Data.EntityState.Deleted)
                    {
                        updateContractUpdateDetails = true;
                    }
                }

                if (updateContractUpdateDetails)
                    foreach (var entry in context.ChangeTracker.Entries())
                    {
                        //Boaz 7-Aug-2012
                        //If any changed was made to a record in any table (entities related to the contract) which has
                        //UpdateDate and UpdateUserID fields, these fields are updated to reflect the change.
                        //These fields are NOT handled by the individual classes committing the changes to the
                        //database - they are handled centrally here to cut-down on the code
                        if (entry.Entity is EFContractRelatedEntryWithUpdate && entry.State != EntityState.Unchanged)
                        //if (entry.Entity is EFContractRelatedEntryWithUpdate)
                        {
                            ((EFContractRelatedEntryWithUpdate)entry.Entity).UpdatingDate = updateDate;
                            ((EFContractRelatedEntryWithUpdate)entry.Entity).UpdatingUserID = UpdatingUserID;
                        }
                    }
            }
            if (updateContractUpdateDetails)
            {
                efContract.ContractUpdateDetail.UpdateDate = updateDate;
                efContract.ContractUpdateDetail.UpdateUserID = UpdatingUserID;
            }
            //We want to keep tracking the changes after calling SaveChanges, for the purpose of auditing
            ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
            objectContext.DetectChanges();
            try
            {
                //Using SaveOptions.None to keep change-tracking... Requires objectContext.DetectChanges() before and objectContext.AcceptAllChanges() after...
                int rowsAffected = objectContext.SaveChanges(SaveOptions.None);
            }
            catch (System.Data.UpdateException updEx)
            {
                if (updEx.InnerException != null)
                    if (updEx.InnerException.Message.Contains("DELETE statement conflicted with the REFERENCE constraint") &&
                        updEx.InnerException.Message.Contains("FK_ContractTodos_ContractActivities"))
                        //{
                        //    Logger.Write(updEx, System.Diagnostics.TraceEventType.Warning);
                        throw new ExceptionDataContractSaveDeleteEventWithAlert();
                    //}
                    else if (updEx.InnerException.Message.Contains("FK_Contracts_Contracts") &&
                        updEx.InnerException.Message.Contains("ParentContractID"))
                        throw new ExceptionDataContractDeleteDeleteContractWithChild();
                    else
                        //{
                        //  Logger.Write(updEx, System.Diagnostics.TraceEventType.Error);
                        throw updEx;
                //}
            }

            if (AuditChanges)
            {
                HistManager histManager = new HistManager();
                int recordsWrittenToHistory = histManager.AuditChanges(updateDate, UpdatingUserID, this.New, this.Deleted, context.ChangeTracker.Entries().Where(e => e.State != System.Data.EntityState.Unchanged || e.Entity is TopContractsEntities.Contract));
            }

            objectContext.AcceptAllChanges();

            long contractIdSaved = -1; //will indicate failure, if no number is set
            foreach (var entry in context.ChangeTracker.Entries())
            {
                Logger.Write("entering the loop - for context.ChangeTracker.Entries()", System.Diagnostics.TraceEventType.Verbose);
                if (entry.Entity is TopContractsEntities.Contract)
                {
                    contractIdSaved = ((TopContractsEntities.Contract)entry.Entity).ContractID;
                }
                if (entry.Entity is TopContractsEntities.ContractDoc)
                {
                    TopContractsEntities.ContractDoc efDoc = entry.Entity as TopContractsEntities.ContractDoc;
                    TopContractsDAL10.ContractDoc doc = this.ContractDocs.SingleOrDefault(d => d.FileName == efDoc.FileName);
                    if (doc != null)
                    {
                        if (doc.New)
                        {
                            doc.EntryId = efDoc.DocumentID; //This is done especially for the process of file copying...
                        }
                    }
                }
            }

            if (this.Deleted)
                return 0;
            return contractIdSaved;
        }