Home > Mobile >  Why db.savechanges is storing the old records also?
Why db.savechanges is storing the old records also?

Time:10-03

I have very weird problem

My code it works fine if I login and use then it save the preferences etc.

But problem starts when I login, do some selections, and logout and login as another user, then upon saving it also remembers the seelctions I had done wfor the other user, the last one and save that also.

How to prevent this?

  public IHttpActionResult Add(UserPreferencesDto model)
    {
        model.UserId = User.Identity.GetUserId();

        var userPreferences = db.UserPreferences.Where(u =>
            u.UserId == model.UserId &&
            u.Key == model.Key.Trim())
          .FirstOrDefault();

        List<int> StatesCollection = new List<int>();

        var param = model.Value.Trim();
        string[] paramSplitted = param.Split(',');

        if (userPreferences != null)
        {              
            if (string.IsNullOrEmpty(userPreferences.Value) == false)
            {
                var trimmedPreferenceValue = userPreferences.Value.Trim('[', ']');
                if (string.IsNullOrEmpty(trimmedPreferenceValue) == false)
                {
                    StatesCollection = trimmedPreferenceValue.Split(',')
                      .Select(s => Convert.ToInt32(s)).ToList<int>();
                }

                if (model.IsStateSelected == false && paramSplitted.Count() == 1 
                    && StatesCollection.Contains(int.Parse(param.Trim())))
                {
                    StatesCollection = StatesCollection.Where(sa => sa != int.Parse(param)).ToList<int>();
                    userPreferences.Value = StatesCollection.Count > 0 ? JsonConvert.SerializeObject(StatesCollection) : "";
                }
                else if (model.IsStateSelected && paramSplitted.Count() == 1 
                    && !StatesCollection.Contains(int.Parse(param)))
                {
                    StatesCollection.Add(int.Parse(param));
                    userPreferences.Value = JsonConvert.SerializeObject(StatesCollection);
                }

            }
            else
            {
                StatesCollection.Add(int.Parse(param));
                userPreferences.Value = JsonConvert.SerializeObject(StatesCollection);
            }
        }
        else
        {
            if (model.IsStateSelected == true)
            {
                //string[] splittedStates = model.Value.Split(',');
                int[] secRolesIds = Array.ConvertAll(paramSplitted, int.Parse);
                model.Value = JsonConvert.SerializeObject(secRolesIds);
                db.UserPreferences.Add(Mapper.Map<UserPreferences>(model));
            }

        }

        db.SaveChanges();

        return Ok();
    }

Even if the preferences exist it goes to the last else.

Update:

Db object creation:

  private ApplicationDbContext db = new ApplicationDbContext();

this at the top of code, right after the class opening.

CodePudding user response:

SaveChanges() in entity framework saves ALL tracked changes.

You would have to explicitly discard changes or use untracked entities, only adding them when you wish to save.

https://docs.microsoft.com/en-us/ef/core/querying/tracking

CodePudding user response:

I think you should make the userPreferences variable null before giving a value to it, this way you could prevent it to have a value from the last execution because you would ensure it became null because you forced it to be. By doing so if there is no result in the database when you try to assign a value to it it will remain null for sure and so it will enter to the if with the if (userPreferences != null) and don't go to the else.

  • Related