0

Ok so I have this query

  public bool Save(PresseViewModel p)
    {
        var presse = PresseService.Instance.Get(p.Id);

        presse.title = p.Title;
        presse.sammenfatning = p.Sammenfatning;
        presse.HTML = p.HTML;

        try
        {
            PresseService.Instance.Save(presse);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

I am trying to update an existing record with only selected fields. The model has 20+ fields but now I am only trying to update 3 fields.

What I did is I fetched first the original record from db, then populate those fields with new values and Save!! then all good!.

Now the problem is

What if the ".Save " failed? and moved to Catch Exception, so as usual nothing will be saved, original values will remain the same right? Ok so move on and ignore it,

Ok now I want to get that same record and populate it to my page, and then weird things happens, it gave me instead incorrect result, the 3 fields it render was the 3 fields I am trying to save previously (but failed to save),

I assume the problem is this line

    var presse = PresseService.Instance.Get(p.Id);

    presse.title = p.Title;
    presse.sammenfatning = p.Sammenfatning;
    presse.HTML = p.HTML

This line will store somewhere in memory (or somewhere else) regardless if it was saved or not, so the next time I query for that ID is it will give that values I set before.

Now my question is how can I avoid it or what is the fix for this, and as much as possible I dont want to force query from database using this line _db.Entry<Pressemeddelelser>(result).Reload();

  • Are you using a singleton context or something? Once the save fails, your context should get destroyed / rolled back, so there shouldn't be an issue with it caching the prior values. Also, as a general rule, swallowing an exception in this manner and just returning false is asking for trouble. I hope that was just to demonstrate your issue and not real code. – stephen.vakil Sep 08 '16 at 16:09
  • @stephen.vakil Yes I am using a singleton, in my situation regardless of it was saved or not it still caching my "supposed to saved values", the save was failed so I am expecting the original results and not the "supposed to saved values". –  Sep 08 '16 at 16:17
  • Possible duplicate? See http://stackoverflow.com/questions/5466677/undo-changes-in-entity-framework-entities – Kim Johnson Sep 08 '16 at 16:22
  • I think this question might be what you are looking for [dbcontext-discard-changes-without-disposing](http://stackoverflow.com/questions/16437083/dbcontext-discard-changes-without-disposing) – Jared Stroebele Sep 08 '16 at 16:50

0 Answers0