title: How to manage versioning of entities in Entity Framework?
body: <p>We have an entity for which we want to save old versions as revisions, what is the best way to achieve this?</p>
  <p>The current idea is to have two properties <code>Id</code> and <code>Revision</code> that combined makes up the primary key. I am not sure if this is the correct approach, and I have issues with how to get the database to generate the values - if I do not set them myself.</p>
  <p>If I save a completely new entity I want both <code>Id</code> and <code>Revision</code> to be set. ´Id´ to the next id in order, and <code>Revision</code> to zero.</p>
  <p>If I save a new version of an entity I would set the <code>Id</code> to the id of the entity I want to create a new revision of (together with all other values I might want to bring over to the new entity). I would like to leave the ´Revision´ property empty, and the database should then increment this and set it to the previous latest revision value + 1.</p>
  <p>How can I achieve this functionality with entity framework? Can I achieve it with entity framework?</p>
  <p><strong>Edit</strong></p>
  <p>I have tried this setup in my <code>DbContext</code> implementation:</p>
  <pre class="lang-cs prettyprint-override"><code>protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
      modelBuilder.Entity&lt;EntityDao&gt;().HasKey(m =&gt; new { m.Id, m.Revision });
      modelBuilder.Entity&lt;EntityDao&gt;().Property(m =&gt; m.Id).ValueGeneratedOnAdd();
      modelBuilder.Entity&lt;EntityDao&gt;().Property(m =&gt; m.Revision).ValueGeneratedOnAdd();
  }
  </code></pre>
  <p>But then I get this error:</p>
  <pre><code>Only one column per table can be configured as 'Identity'. 
  </code></pre>
  <p>If I remove the <code>ValueGeneratedOnAdd</code> statement on the <code>Revision</code> property, the service is able to start. But then I get an error on save since <code>Revision</code> is null - unless I manually give it a value.</p>
  <p>There was also an issue that I could not explicitly set the <code>Id</code> property when I had the <code>ValueGeneratedOnAdd</code> statement. I got the following error:</p>
  <pre><code>Cannot insert explicit value for identity column in table 'Entities' when IDENTITY_INSERT is set to OFF.
  </code></pre>
  <p>But I found this info on how to solve that:
  <a href="https://docs.microsoft.com/en-us/ef/core/saving/explicit-values-generated-properties#explicit-values-into-sql-server-identity-columns" rel="nofollow noreferrer">explicit-values-generated-properties</a></p>