i reading seeding database, , wonder, if create seed 10 items, every time migrate or update database, reseeded, have 20 items in database?
i want seed x items, constant in database, how do it?
thanks.
in seed method should use addorupdate
method.
imagine populating table of countries. have code in seed method this:
context.countries.addorupdate( c => c.code, new country { code = "ca", description = "canada" }, new country { code = "us", description = "united states" });
each time code runs ef query db see if country exists matching code
column. if not, insert, otherwise attempt update country current values in seed method.
let's you've run update-database
, above data has been created. change "united states" "united states of america". 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 run update-database
ef won't create new country row. update existing row code == "us"
.
one further thing note not use c => c.id
identifierexpression
(the first argument). reason being ids typically use identity specification, meaning value gets generated database. therefore not reliable way of determining matching row. i've seen done number of times, , result duplicated records in database.
so clarity, don't this:
context.foos.addorupdate( x => x.id, new foo { id = 1, value = "don't this" });
the id put in object initializer won't used when row created. generated value used instead. however, id specified will used when ef trying find match later (for updates). extremely unlikely ids match, , ef rightfully think has create new row, duplicating data.