I am using Entity Framework (Database First) and I am trying to import a bunch of data from an old database into our new one. In some instances it is important for the object IDs to remain the same in the new database as they are in the old one. Normally when you create a new object and call context.SaveChanges() it will automatically assign an identity value to the ID column.
Currently, what is happening is that I will set the new object ID in code, but once I call context.SaveChanges() it is overwritten by the new one assigned by Entity Framework.
I need to be able to set the ID in the new object manually and have it remain once I call context.SaveChanges().
EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. The above example will execute the following SQL in the database. WHERE @@ROWCOUNT = 1 AND [StudentID] = scope_identity();
To insert explicit values into a SQL Server IDENTITY column, you need to manually enable IDENTITY_INSERT before calling SaveChanges() . The following example demonstrates how to set an explicit value to an id property. In the above example, we first saved a new Student with the DB-generated StudentId .
The Database Generated Option can also be specified as an attribute of the property itself, rather than by using the fluent API.
public class Foo
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public virtual int Id { get; set;}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With