Reputation: 103
I am reading this about seeding a database, and I wonder, if I create a seed with 10 items, every time I migrate or update the database, will it be reseeded, so that I now have 20 items in my database?
I want to seed X items, that are constant in my database, how do I do it?
THanks.
Upvotes: 1
Views: 107
Reputation: 11380
In your seed method you should use the AddOrUpdate
method.
Imagine you are populating a table of Countries. You would have code in your seed method like this:
context.Countries.AddOrUpdate(
c => c.Code,
new Country { Code = "CA", Description = "Canada" },
new Country { Code = "US", Description = "United States" });
Each time this code runs EF will query the DB to see if a country exists with a matching Code
column. If not, it will do an INSERT, otherwise it will attempt to update the Country with the current values in the seed method.
Let's say you've already run update-database
and the above data has been created. Then you change "United States" to "United States of America". Like this:
context.Countries.AddOrUpdate(
c => c.Code,
new Country { Code = "CA", Description = "Canada" },
new Country { Code = "US", Description = "United States of America" });
The next time you run update-database
EF won't create a new Country row. It will just update the existing row with Code == "US"
.
One further thing to note is to not use c => c.Id
as your identifierExpression
(the first argument). Reason being is Ids typically use the IDENTITY specification, meaning its value gets generated by the database. Therefore it is not a reliable way of determining a matching row. I've seen this done a number of times, and the result is always duplicated records in the database.
So for clarity, DON'T DO THIS:
context.Foos.AddOrUpdate(
x => x.Id,
new Foo { Id = 1, Value = "Don't do this" });
The Id you put in the object initializer won't be used when the row is created. A generated value will be used instead. However, the Id you specified will be used when EF is trying to find a match later (for updates). It is extremely unlikely the IDs will match, and EF will rightfully think it has to create a new row, thus duplicating your data.
Upvotes: 1
Reputation: 34987
Short answer
In order to keep ten items you will need to check for their presence in your Seed method.
Slightly longer answer
Msdn DbMigrationsConfiguration.Seed Method states
Note that the database may already contain seed data when this method runs. This means that implementations of this method must check whether or not seed data is present and/or up-to-date and then only make changes if necessary and in a non-destructive way.
Upvotes: 0