Esempio n. 1
0
        public ActionResult SaveUserData(UserDataViewModel model)
        {
            UserData ud = model.ToUserData();
            //db.Entry(ud).State = System.Data.EntityState.Modified;

            if (db.UserData.Find(WebSecurity.CurrentUserId) != null)
            {
                var additionalInfo = from userAddInfo in db.UserData.Find(model.UserId).UserProperties select userAddInfo;
                if (model.UserProperties == null)
                {
                    for (; additionalInfo.Count() > 0; )
                        db.Entry(additionalInfo.First()).State = System.Data.EntityState.Deleted;

                }
                else
                {
                    if (additionalInfo.Count() != 0)
                    {
                        List<int> toDelete = new List<int>();
                        foreach (var item in additionalInfo)
                        {
                            if (model.UserProperties.Find(obj => obj.Id == item.Id) == null) toDelete.Add(item.Id);
                        }
                        for (int i = 0; i < toDelete.Count; i++)
                        {
                            db.Entry(additionalInfo.First(item => item.Id == toDelete[i])).State = System.Data.EntityState.Deleted;
                        }
                    }
                    foreach (var item in ud.UserProperties)
                    {
                        if (item.UserId == 0)
                        {
                            item.UserId = WebSecurity.CurrentUserId;
                            db.Entry(item).State = System.Data.EntityState.Added;
                        }
                    }
                }
                if (model.Picture != null)
                {
                    try
                    {
                        if (db.UserData.Find(WebSecurity.CurrentUserId).Images != null)
                            db.Entry(db.UserData.Find(WebSecurity.CurrentUserId).Images).State = System.Data.EntityState.Deleted;
                    }
                    finally
                    {
                        db.Images.Add(ud.Images);
                        //db.Entry(ud).State = System.Data.EntityState.Modified;
                    }
                }
                db.SaveChanges();
                if (ud.Images != null)
                {
                    db.UserData.Find(WebSecurity.CurrentUserId).PictureId = ud.Images.Id;
                    db.Entry(db.UserData.Find(WebSecurity.CurrentUserId)).State = System.Data.EntityState.Modified;
                    db.SaveChanges();
                }
            }
            else
            {
                db.UserData.Add(ud);
                db.SaveChanges();
            }

            return RedirectToAction("Manage");
        }