I am moving the legacy database to the new database that we need for access and "management" (as oxymoronic, as it may sound), primarily through the Entity Framework Code-First.
We are using MS SQL Server 2014.
The inherited database contained several tables with columns with calculation . Typical GUID and DateTime properties.
From a technical point of view, these columns did not have a computed column specification, but rather, when the default value is set with NEWID() and GETDATE()
We all know that it is very easy to configure DbContext to solve these properties as follows:
modelBuilder.Entity<Foo>() .Property(t => t.Guid) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed); modelBuilder.Entity<Bar>() .Property(t => t.DTS) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
The above instructed the Entity Framework to ignore sending any setpoints for such properties during INSERTs and UPDATEs .
But now we need to enable the import of obsolete records and support OLD values , including the PRIMARY KEY , which is marked as IDENTITY
This means that we would have to set the Id , Guid and DTS properties in DatabaseGeneratedOption.None when inserting these records.
In the case of Id we need to somehow execute SET IDENTITY_INSERT ... ON/OFF in the communication session.
And we want to do this import through Code-First.
If I change the model and "temporarily" and set these properties to DatabaseGeneratedOption.None after creating the database, we get the typical one:
The context-supporting model has changed since the database was created. Consider using First First Migrations to upgrade your database.
I understand that we could generate an empty encoded migration using -IgnoreChanges to βinstallβ this latest version of the context, but this would not be an acceptable strategy, since we would need to run empty migrations back and forth exclusively for this purpose.
Half the answer:
We considered the possibility of assigning these properties to types with a zero value, i.e.
public class Foo { ... public Guid? Guid { get; set; } } public class Bar { ... public DateTime? DTS { get; set; } }
Holding the defaults in the initial DbMigration :
CreateTable( "dbo.Foos", c => new { Id = c.Int(nullable: false, identity: true), Guid = c.Guid(nullable: false, defaultValueSql: "NEWID()"), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Bars", c => new { Id = c.Int(nullable: false, identity: true), DTS = c.Guid(nullable: false, defaultValueSql: "GETDATE()"), }) .PrimaryKey(t => t.Id);
Question:
But the question remains: is there a way to switch between DatabaseGeneratedOption.Identity , DatabaseGeneratedOption.Computed and DatabaseGeneratedOption.None at runtime?
At least how could we enable / disable DatabaseGeneratedOption.Identity at runtime?