Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you're trying to retrieve the original record in code, <strong>from the same 'context'</strong> using the same access method, then it will contain the updated object. Rather than ask why you're doing this or what you're trying to achieve, I'll instead explain how I understand the data context / object context to work (in a very loose and vague fashion).</p> <p>The context is something like an in-memory representation of your database, where everything is lazy-loaded. When you instantiate the context you're given an object which represents your data model (of course it may not be a 1-1 representation, and can contain various abstractions). Nothing is loaded into the context until necessary; any queries you write stay as queries until you peer in their results. When you access an item (e.g. <code>GetobjectById(objectToEdit.Id)</code>) the item is loaded into the context from the database and you can <code>get</code> and <code>set</code> its properties at your leisure.</p> <p><strong>Now, the important part:</strong> When you access an item, if it has already been loaded into the context then that in-memory object is returned. The context doesn't care about checking changes made; the changes won't be persisted to the database until you submit, but they remain in memory.</p> <p>The way to refresh the in-memory objects is to call the <code>Refresh</code> method on the context. Try this test:</p> <pre><code>using (var db = new MyObjectContext()) { var item = db.Items.First(); item.Name = "testing this thing"; Console.WriteLine(db.Shifts.First().Name); db.Refresh(System.Data.Objects.RefreshMode.StoreWins, db.Items); Console.WriteLine(db.Shifts.First().Name); } </code></pre> <p>I believe this pattern makes a lot of sense and I'm not sure it could work any other way. Consider this:</p> <pre><code>foreach (var item in db.Items) { item.Name = "test"; } Assert(db.Items.All(item =&gt; item.Name == "test")); </code></pre> <p>Would you want the <code>Assert</code> to fail? Should those items be reloaded? I don't believe so. I'm looking at the items in my context, not in the database. I'm not checking whether items in the database have been updated, but instead that I've updated all the items in the context of my code.</p> <p>This is a good reason why I don't use <code>MyObjectContext db</code> - it is <strong>not</strong> a 'db' or a database connection. It's a context within which I can change whatever I want, so I name it such: <code>MyObjectContext context</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload