This repository has been archived by the owner on Jul 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
441 lines (186 loc) · 11.9 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
<!DOCTYPE html>
<!--[if IEMobile 7 ]><html class="no-js iem7"><![endif]-->
<!--[if lt IE 9]><html class="no-js lte-ie8"><![endif]-->
<!--[if (gt IE 8)|(gt IEMobile 7)|!(IEMobile)|!(IE)]><!--><html class="no-js" lang="en"><!--<![endif]-->
<head>
<meta charset="utf-8">
<title>EF ObjectContext.Attach and ObjectStateManager - Felipe Lima</title>
<meta name="author" content="Felipe Lima">
<meta name="description" content="When working with the Entity Framework, you’ve got to be extremely careful when exchanging Entities between different ObjectContexts. You …">
<!-- http://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="canonical" href="http://felipecsl.github.com/blog/2009/07/02/ef-objectcontext-attach-and-objectstatemanager/">
<link href="/favicon.png" rel="icon">
<link href="/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">
<script src="/javascripts/modernizr-2.0.js"></script>
<script src="/javascripts/ender.js"></script>
<script src="/javascripts/octopress.js" type="text/javascript"></script>
<link href="/atom.xml" rel="alternate" title="Felipe Lima" type="application/atom+xml">
<!--Fonts from Google"s Web font directory at http://google.com/webfonts -->
<link href="http://fonts.googleapis.com/css?family=PT+Serif:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=PT+Sans:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css">
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-26310657-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body >
<header role="banner"><hgroup>
<h1><a href="/">Felipe Lima</a></h1>
<h2>weblog</h2>
</hgroup>
</header>
<nav role="navigation"><ul class="subscription" data-subscription="rss">
<li><a href="/atom.xml" rel="subscribe-rss" title="subscribe via RSS">RSS</a></li>
</ul>
<form action="http://google.com/search" method="get">
<fieldset role="search">
<input type="hidden" name="q" value="site:felipecsl.github.com" />
<input class="search" type="text" name="q" results="0" placeholder="Search"/>
</fieldset>
</form>
<ul class="main-navigation">
<li><a href="/">Blog</a></li>
<li><a href="/blog/archives">Archives</a></li>
</ul>
</nav>
<div id="main">
<div id="content">
<div>
<article class="hentry" role="article">
<header>
<h1 class="entry-title">EF ObjectContext.Attach and ObjectStateManager</h1>
<p class="meta">
<time datetime="2009-07-02T00:30:00-07:00" pubdate data-updated="true">Jul 2<span>nd</span>, 2009</time>
</p>
</header>
<div class="entry-content"><p>When working with the Entity Framework, you’ve got to be extremely careful when exchanging Entities between different ObjectContexts. You probably know that if you want to modify an Entity which is already added to the database, you have to first attach it to the context before modifying it, so that EF can keep track of the changes you made to that instance and save them to the database later. There is a good reference page at msdn about <a href="http://msdn.microsoft.com/en-us/library/bb896271.aspx">attaching related objects</a>.</p>
<p>Attach assumes your Entity has not been changed while it was not being tracked by the ObjectContext. Otherwise, call <strong>ApplyPropertyChanges</strong> to attach and apply the changes.</p>
<p>Yesterday, I lost almost my entire day trying to translate this exception I was getting in ObjectContext.Attach():</p>
<p>“<strong>System.InvalidOperationException : An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.</strong>”</p>
<p>EF complains that the Entity you’re trying to add actually has an EntityKey identical to one that is already in the database. Okay, this seems obvious to me, since this is the actual purpose of Attach – start tracking changes objects that already exist in the database.</p>
<p>After an entire afternoon searching for an answer, I came accross some pages with other issues related to Attach that some people had, as well some solutions for <a href="http://www.codeproject.com/KB/architecture/attachobjectgraph.aspx">them</a>.</p>
<p>Today I re-read the exception message and the answer just popped on my face: “<strong>I’m already tracking the object you’re trying to Attach, dumbass!</strong>”. In fact, you cannot Attach an object to an ObjectContext if that object somehow has been already cached by the ObjectStateManager.</p>
<p>Let me exemplify:</p>
<pre><code><span class="lnum"> 1: </span><span class="kwrd">public</span> <span class="kwrd">void</span> UpdateUserBooks(User _user)
<span class="lnum"> 2: </span>{
<span class="lnum"> 3: </span> <span class="kwrd">using</span> (DataEntities db = <span class="kwrd">new</span> DataEntities())
<span class="lnum"> 4: </span> {
<span class="lnum"> 5: </span> Book userBook = (from b <span class="kwrd">in</span> db.Book.Include(<span class="str">"Users"</span>)
<span class="lnum"> 6: </span> select b).FirstOrDefault();
<span class="lnum"> 7: </span>
<span class="lnum"> 8: </span> db.Attach(_user); <span class="rem">// throws InvalidOperationException</span>
<span class="lnum"> 9: </span> userBook.Users.Add(_user);
<span class="lnum"> 10: </span> db.SaveChanges();
<span class="lnum"> 11: </span> }
<span class="lnum"> 12: </span>}
</code></pre>
<p>What is happening? Your userBook query returns all the Books from the database <strong>AND</strong> their related Users (the Include was there for a reason). When you try to attach your User after_user after the query has been run, the ObjectContext already has _user under its hood, so trying to Attach it will throw an InvalidOperationException.</p>
<p>The solution is very simple: Always attach all your Entities before doing any operation/query in your ObjectContext. This way, you avoid any double-tracking request. If the ObjectContext needs your Entity later, it will retrieve the instance you attached before and you’re good to go! Follow the fixed code:</p>
<pre><code><span class="lnum"> 1: </span><span class="kwrd">public</span> <span class="kwrd">void</span> UpdateUserBooks(User _user)
<span class="lnum"> 2: </span>{
<span class="lnum"> 3: </span> <span class="kwrd">using</span> (DataEntities db = <span class="kwrd">new</span> DataEntities())
<span class="lnum"> 4: </span> {
<span class="lnum"> 5: </span> db.Attach(_user); <span class="rem">// works fine!</span>
<span class="lnum"> 6: </span>
<span class="lnum"> 7: </span> Book userBook = (from b <span class="kwrd">in</span> db.Book.Include(<span class="str">"Users"</span>)
<span class="lnum"> 8: </span> select b).FirstOrDefault();
<span class="lnum"> 9: </span>
<span class="lnum"> 10: </span> userBook.Users.Add(_user);
<span class="lnum"> 11: </span> db.SaveChanges();
<span class="lnum"> 12: </span> }
<span class="lnum"> 13: </span>}
</code></pre>
</div>
<footer>
<p class="meta">
<span class="byline author vcard">Posted by <span class="fn">Felipe Lima</span></span>
<time datetime="2009-07-02T00:30:00-07:00" pubdate data-updated="true">Jul 2<span>nd</span>, 2009</time>
</p>
<div class="sharing">
<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://felipecsl.github.com/blog/2009/07/02/ef-objectcontext-attach-and-objectstatemanager/" data-via="felipecsl" data-counturl="http://felipecsl.github.com/blog/2009/07/02/ef-objectcontext-attach-and-objectstatemanager/" >Tweet</a>
</div>
<p class="meta">
<a class="basic-alignment left" href="/blog/2009/06/24/notimplementedexception-in-graphics-drawimage/" title="Previous Post: NotImplementedException in Graphics.DrawImage">« NotImplementedException in Graphics.DrawImage</a>
<a class="basic-alignment right" href="/blog/2009/07/08/automatically-tracking-last-modification-datetime-in-table-column/" title="Next Post: Automatically tracking last modification date/time in table column">Automatically tracking last modification date/time in table column »</a>
</p>
</footer>
</article>
</div>
<aside class="sidebar">
<section>
<h1>Recent Posts</h1>
<ul id="recent_posts">
<li class="post">
<a href="/blog/2013/03/31/starting-with-android-managing-images/">Starting with Android - managing images</a>
</li>
<li class="post">
<a href="/blog/2012/07/31/when-two-identical-strings-are-different/">When two identical strings are different?</a>
</li>
<li class="post">
<a href="/blog/2012/06/14/getting-started-with-chef/">Getting started with Chef</a>
</li>
<li class="post">
<a href="/blog/2012/06/05/protip-delete-words-on-iterm2-mac-osx/">Protip: Delete words on iTerm2 (Mac OSX)</a>
</li>
<li class="post">
<a href="/blog/2012/05/24/wombat-0-4-0-released/">Wombat 0.4.0 released!</a>
</li>
</ul>
</section>
<section>
<h1>GitHub Repos</h1>
<ul id="gh_repos">
<li class="loading">Status updating...</li>
</ul>
<a href="https://github.com/felipecsl">@felipecsl</a> on GitHub
<script type="text/javascript">
$.domReady(function(){
if (!window.jXHR){
var jxhr = document.createElement('script');
jxhr.type = 'text/javascript';
jxhr.src = '/javascripts/libs/jXHR.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(jxhr, s);
}
github.showRepos({
user: 'felipecsl',
count: 4,
skip_forks: true,
target: '#gh_repos'
});
});
</script>
<script src="/javascripts/github.js" type="text/javascript"> </script>
</section>
<a href="mailto:felipe.lima@gmail.com" title="Pair program with me!">
<img src="http://pairprogramwith.me/badge.png"
alt="Pair program with me!" style="width: 150px" />
</a>
</aside>
</div>
</div>
<footer role="contentinfo"><p>
Copyright © 2013 - Felipe Lima -
<span class="credit">Powered by <a href="http://octopress.org">Octopress</a></span>
</p>
</footer>
<script type="text/javascript">
(function(){
var twitterWidgets = document.createElement('script');
twitterWidgets.type = 'text/javascript';
twitterWidgets.async = true;
twitterWidgets.src = 'http://platform.twitter.com/widgets.js';
document.getElementsByTagName('head')[0].appendChild(twitterWidgets);
})();
</script>
</body>
</html>