Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - set ID of new object manually

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().

like image 263
jdavis Avatar asked Mar 29 '12 21:03

jdavis


People also ask

How do I get an ID after inserting EF core?

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();

How do you set an explicit value to ID property in EF core?

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 .


1 Answers

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;}
}
like image 112
Eric J. Avatar answered Oct 21 '22 11:10

Eric J.