Search code examples
c#entity-frameworkef-code-firstcode-first

Seed is wiping out existing data


I have a table with a fix number of rows, 51 one for every US state plus DC. In addition to the StateCode column there is some per-state data as well. But the number of rows will not change.

StateCode    DataColum1    DataColumn2   etc

When the db is seeded, I need to populate the table with the the 51 rows if they don't exist. But if they do, I need to leave the table alone.

The way I am currently doing it wipes out all the data every time I do a database-update.

context.StateLeadSettings.AddOrUpdate(s => s.StateCode,
    new StateLeadSettings() { StateCode = "AK" },
    ....
 );

Not sure how to change this so it only adds if they don't exist.


Solution

  • Try this logic:

    var stateLeadSettings = new List<StateLeadSettings>{
        new StateLeadSettings() { StateCode = "AK" },
        ....
    };
    var codes = stateLeadSettings.Select(x => x.StateCode).ToList();
    var existed = context.StateLeadSettings.Where(x => codes.Contains(x.StateCode))
                    .Select(x => x.StateCode).ToList();
    context.StateLeadSettings.AddRange(stateLeadSettings
                    .Where(x => !existed.Contains(x.StateCode)).ToList());
    context.SaveChanges();