Skip to content

Commit ba09cb3

Browse files
committed
Add anecdote
1 parent 788f609 commit ba09cb3

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

_posts/2024-06-03-youll-regret-using-natural-keys.html

+16
Original file line numberDiff line numberDiff line change
@@ -301,4 +301,20 @@ <h2 id="comments-header">
301301
</div>
302302
<div class="comment-date">2024-06-14 13:45 UTC</div>
303303
</div>
304+
305+
<div class="comment" id="fee47871b1494293b039b67d21187e6b">
306+
<div class="comment-author">Julius H <a href="#fee47871b1494293b039b67d21187e6b">#</a></div>
307+
<div class="comment-content">
308+
<p>I'd like to comment with an example where using a synthetic key came back to bite me. My system had posts and users with synthetic IDs. Now I wanted to track an unread state across them. Naively, I designed just another entity:</p>
309+
<pre>
310+
public int ID { get; set; }
311+
public int PostID { get; set; }
312+
public int UserID { get; set; }
313+
</pre>
314+
<p>And it worked flawlessly for years. One day, however, a user complained that he always got an exception "Sequence contains more than one element". Of course I used SingleOrDefault() in application code because I expected 0 or 1 record per user and post.
315+
The quick solution was deleting the spurious table row. As a permanant solution I removed the ID field (and column) so the unread state had its natural key as primary key (both columns). So if it happens again in the future, the app will error on insertin rather than querying.</p>
316+
<p>Since my application is in control of the IDs and it's just a very simple join table I think it was the best solution. If the future requirements hold different kinds of unread state, I can always add the key again.</p>
317+
</div>
318+
<div class="comment-date">2024-07-22 14:40 UTC</div>
319+
</div>
304320
</div>

0 commit comments

Comments
 (0)