I have a POCO that I am trying to create via Code First Migrations and then seed data. The problem is that I want to insert specific values into the identity column when seeding.
Here is my POCO
public class Result
{
public long ResultId { get; set; }
public long? TeamId { get; set; }
public Team Team { get; set; }
}
And here is my AddOrUpdate call in the Seed method of the Configuration.cs
context.Results.AddOrUpdate
(
r => r.ResultId,
new Result { ResultId = 101, TeamId = null },
new Result { ResultId = 201, TeamId = null }
);
As expected, it does not insert the values of 101 and 201, but instead 1 and 2. Are there any DataAttributes I can apply to the model to help with this?
In case anyone is still confused . . .
See below for additional info required to get IDENTITY_INSERT to work with Code-First Migration Seed() method
I did use Aron's implementation of the
System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated
attribute to set the model ID's DB-generated property to 'None', but I still could not get past the identity insert error. I figured I would post my findings here in case anyone else is still having trouble.To get it to work, I wrapped the seed method's logic in a SQL transaction and used
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT myTable ON")
to allow the insert prior to running the.AddOrUpdate()
method. Here is my Configuration.vb file (using a table for Google API types as our example data):After researching into this it looks like if the key was previously created and then you add [DatabaseGenerated(DatabaseGeneratedOption.None)] in a migration it wont actually do what you intend, you can check this by going to the database explorer Table -> Keys -> PK -> Modify and see the Identity Specification is set to Yes instead of No.
If this is the case try migrating down to a point where that table did not exist and then remigrate back up.
This how to turn off Identity via attribute/conventions
This is how you turn off Identity via EntityTypeConfiguration
Or you can use the OnModelCreating overload
If you are using AutoMapper and using for/foreach mode, you must remap in for loop.
Example: