Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is nothing wrong with designing a class so that an ID of 0 indicates that the entity has not yet been serialized. I have built systems in the past that successfully used this approach. Just make sure that these semantics are well defined in your API, and that this meaning is respected in all of the code.</p> <p>One trap to watch out for is using the ID to define an equality relationship (such as for generating hash codes for a dictionary). This must only be done for non-zero IDs. For testing equality with two IDs of zero, reference equality may be used.</p> <p>However, since unstored entities may have their ID change at some point in the future, it is very important that such objects are never stored in a Dictionary. Or, at the very least, such items must be removed from any dictionaries before saving and then restored afterwards using the new ID.</p> <p>With that one reservation, this design should work fine.</p> <pre><code>public class Test : IEquatable&lt;Test&gt; { /// &lt;summary&gt; /// The unique identifier for this Test entity, or zero if this /// Test entity has not yet been serialized to the database. /// &lt;/summary&gt; public int Id { get; private set; } public string Something { get; set; } public override bool Equals(object obj) { return Equals(obj as Test); } public bool Equals(Test other) { if (other == null) return false; // Distinct entities may exist with the Id value of zero. if (Id == 0) return object.ReferenceEquals(this, other); return Id == other.Id; } /// &lt;summary&gt; /// Gets a hash code for this Test entity. Warning: an instance with /// an Id of zero will change its identity when saved to the DB. Use with care. /// &lt;/summary&gt; /// &lt;returns&gt;The hash code.&lt;/returns&gt; public override int GetHashCode() { return Id; } } </code></pre>
    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. 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