Whenever an entity which inherits from HistoricalData
is changed, I want to do an insert instead of an update.
This is the abstract base class with Key {VersionID, ParentID}
:
public abstract class HistoricalData
{
public int VersionID { get; set; }
public Guid ParentID { get; set; }
public DateTime ValidFrom { get; set; }
}
This is my approach in the DbContext
:
public override Task<int> SaveChangesAsync()
{
foreach (var entry in ChangeTracker.Entries<HistoricalData>().Where(e => e.State == EntityState.Modified))
{
InsertInsteadOfUpdate(entry);
}
return base.SaveChangesAsync();
}
private void InsertInsteadOfUpdate(DbEntityEntry<HistoricalData> entry)
{
// ValidFrom is not set manually -> Set it automatically to now
if (entry.OriginalValues["ValidFrom"].Equals(entry.CurrentValues["ValidFrom"]))
{
entry.Entity.ValidFrom = DateTime.Now;
}
// Insert instead of Update
entry.CurrentValues["VersionID"] = null;
entry.State = EntityState.Added;
}
I change the VersionID
, because it is an Identity Column and I want the database to create a new value for the insert.
However, I get the following Exception:
System.InvalidOperationException: The property 'VersionID' is part of the object's key information and cannot be modified.
If I don't try to modify VersionID
, the Insert fails with a DuplicateKey Exception.
Is there any way to change a DbEntityEntry from Modified to Added with a new ID?