Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h3>If you're expecting a Single record, it's always good to be explicit in your code.</h3> <p>I know others have written why you use one or the other, but I thought I'd illustrate why you should NOT use one, when you <strong>mean</strong> the other.</p> <p><em>Note: In my code, I will typically use <code>FirstOrDefault()</code> and <code>SingleOrDefault()</code> but that's a different question.</em></p> <p>Take, for example, a table that stores <code>Customers</code> in different languages using a Composite Key ( <code>ID</code>, <code>Lang</code> ): </p> <pre><code>DBContext db = new DBContext(); Customer customer = db.Customers.Where( c=&gt; c.ID == 5 ).First(); </code></pre> <p>This code above introduces a possible logic error ( difficult to trace ). It will return more than one record ( assuming you have the customer record in multiple languages ) but it will always return only the first one... which may work sometimes... but not others. It's unpredictable.</p> <p>Since your intent is to return a Single <code>Customer</code> use <code>Single()</code>;</p> <p>The following would throw an exception ( which is what you want in this case ):</p> <pre><code>DBContext db = new DBContext(); Customer customer = db.Customers.Where( c=&gt; c.ID == 5 ).Single(); </code></pre> <p>Then, you simply hit yourself on the forehead and say to yourself... OOPS! I forgot the language field! Following is the correct version:</p> <pre><code>DBContext db = new DBContext(); Customer customer = db.Customers.Where( c=&gt; c.ID == 5 &amp;&amp; c.Lang == "en" ).Single(); </code></pre> <p><code>First()</code> is useful in the following scenario:</p> <pre><code>DBContext db = new DBContext(); NewsItem newsitem = db.NewsItems.OrderByDescending( n =&gt; n.AddedDate ).First(); </code></pre> <p>It will return ONE object, and since you're using sorting, it will be the most recent record that is returned.</p> <p>Using <code>Single()</code> when you feel it should explicitly always return 1 record will help you avoid logic errors.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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