public void Update(Role rol, List <User> lstUsrs)
        {
            var existingParent = base.Context.Set <Role>().Where(p => p.Id == rol.Id)
                                 .Include(p => p.Users).Include(p => p.FormAccesses).SingleOrDefault();

            if (existingParent != null)
            {
                // Update parent
                base.Context.Entry(existingParent).CurrentValues.SetValues(rol);

                // Delete Old Users
                foreach (var existingChild in existingParent.Users.ToList())
                {
                    IObjectContextAdapter contextAdapter = (IObjectContextAdapter)base.Context;
                    System.Data.Entity.Core.Objects.ObjectStateManager stateManager = contextAdapter.
                                                                                      ObjectContext.ObjectStateManager;
                    stateManager.ChangeRelationshipState(existingParent, existingChild, "Users", EntityState.Deleted);
                }
                //Add New Users
                List <User> lstUsers = new List <User>();
                foreach (User usr in lstUsrs)
                {
                    lstUsers.Add((User)base.Context.Set(typeof(User)).Find(usr.Id));
                }
                base.Context.Entry(existingParent).Collection("Users").CurrentValue = lstUsers;
                base.Context.SaveChanges();
            }
        }
Esempio n. 2
0
        public void Update(User usr, int[] lstRol)
        {
            var existingParent = base.Context.Set <User>().Where(p => p.Id == usr.Id)
                                 .Include(p => p.Roles).SingleOrDefault();

            if (existingParent != null)
            {
                // Update parent
                base.Context.Entry(existingParent).CurrentValues.SetValues(usr);

                // Delete Old children
                foreach (var existingChild in existingParent.Roles.ToList())
                {
                    IObjectContextAdapter contextAdapter = (IObjectContextAdapter)base.Context;
                    System.Data.Entity.Core.Objects.ObjectStateManager stateManager = contextAdapter.
                                                                                      ObjectContext.ObjectStateManager;
                    stateManager.ChangeRelationshipState(existingParent, existingChild, "Roles", EntityState.Deleted);
                }
                List <Role> lstRoles = new List <Role>();
                foreach (int id in lstRol)
                {
                    lstRoles.Add((Role)base.Context.Set(typeof(Role)).Find(id));
                }
                base.Context.Entry(existingParent).Collection("Roles").CurrentValue = lstRoles;
                base.Context.SaveChanges();
            }
        }