Reputation: 2058
We have an entity for which we want to save old versions as revisions, what is the best way to achieve this?
The current idea is to have two properties Id
and Revision
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.
If I save a completely new entity I want both Id
and Revision
to be set. ´Id´ to the next id in order, and Revision
to zero.
If I save a new version of an entity I would set the Id
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.
How can I achieve this functionality with entity framework? Can I achieve it with entity framework?
Edit
I have tried this setup in my DbContext
implementation:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EntityDao>().HasKey(m => new { m.Id, m.Revision });
modelBuilder.Entity<EntityDao>().Property(m => m.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<EntityDao>().Property(m => m.Revision).ValueGeneratedOnAdd();
}
But then I get this error:
Only one column per table can be configured as 'Identity'.
If I remove the ValueGeneratedOnAdd
statement on the Revision
property, the service is able to start. But then I get an error on save since Revision
is null - unless I manually give it a value.
There was also an issue that I could not explicitly set the Id
property when I had the ValueGeneratedOnAdd
statement. I got the following error:
Cannot insert explicit value for identity column in table 'Entities' when IDENTITY_INSERT is set to OFF.
But I found this info on how to solve that: explicit-values-generated-properties
Upvotes: 0
Views: 4636
Reputation: 943
As for me the better option would be to create another versions table where you can store all of the entity versions with the entity id foreign key. And when you create completely new entity you just put it in the main table, but when you modify entity you just store existing entity inside versions table with foreign key, and update your entity in the main table. With that approach you would have the main table with only last versions of entities, so you don't need to filter them on get. And versions table from where you always can get all the versions with timestamp and some additional info that you want to have.
Upvotes: 2