Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control primary key values when seeding data with Entity Framework codefirst

I am creating an asp.net mvc4 site using entity framework 5 with codefirst and sql server express 2012.

I have enabled migrations and now do this in my Configuration.Seed method: (note that I want to set the primary key to 8 even though this is the first record in the database).

context.ProductCategoryDtoes.AddOrUpdate(x => x.Id,
    new ProductCategoryDto() { Id = 8, Name = "category1" }
);

My Model object is defined like this:

[Table("ProductCategory")]
public class ProductCategoryDto {
    public long Id { get; set; }
    public string Name { get; set; }
}

This results in a table in (SQL SERVER EXPRESS 2012) where the Id column has Identity = true, Identity seed = 1, identity increment = 1.

Now when I run migrations by doing an PM> Update-Database this result in a row with Id = 1.

So my question are:

1) How can I control the values of auto incremented primary keys when seeding data.

2) If the solution is to increment the key columns seed value, then how is this to be done when I am using Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());. This will nuke and rebuild the database everytime I update the database, so how would the seed value be updated in the fresh database?

like image 582
Stig Schmidt Nielsson Avatar asked Oct 03 '12 08:10

Stig Schmidt Nielsson


People also ask

How do you configure a primary key for an entity in Entity Framework fluent API?

Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.

What is running seed method in Entity Framework?

The Seed method takes the database context object as an input parameter, and the code in the method uses that object to add new entities to the database. To seed data into your database, you need to override the Seed method.

What is data seeding in EF core?

Data seeding is the process of populating a database with an initial set of data. There are several ways this can be accomplished in EF Core: Model seed data. Manual migration customization. Custom initialization logic.


1 Answers

Just create dummy entities with default values, then add your real data and afterwards delete the dummies. Not the best way but I guess there is no other...

like image 95
Sym Phys Avatar answered Oct 12 '22 18:10

Sym Phys