Question

For a while I've been trying to find a solution as to how I could use the seed method in the migration configuration without fear of updated data being overwritten next time the seed method is run.

In short my understanding is that the addorupdate, as demonstrated in various tutorials, will reset all values for each object hence overwriting any changes that may have occurred to that object since it was initially seeded.

In my current project I want to be able to seed a set of default emailtemplates. Putting them in the seed method will assure that they are always present in my code. However, I want the user of the application to be able to edit some of the content as they see fit. So I can't very well have the template being reset everything the seed method runs as it would delete changes.

My solution is this:

    protected override void Seed(Jobboard.Sandbox.Model.JobboardContext context)
    {
        Guid DefaultTemplateGuid = Guid.Parse("xxxxx");

        context.Templates.AddOrUpdate(
              t => t.Guid,
                  context.Templates.FirstOrDefault(x => x.Guid == DefaultTemplateGuid)
                  ?? new Template {
                     Guid = DefaultTemplateGuid,
                     Name = "Default Template",
                     Content = "Some Default Content"
                  }
        );
    }

All in all this seems to work just fine and my question is if anyone can spot any issues doing the seed this way as it's not exactly the way the EF team suggests using this feature and I would prefer not ending up with a headache over this later on.

Many thanks for reading.

Was it helpful?

Solution

You can probably save a few trips to the database by not using the AddOrUpdate extension method. Here is a simplified version of your code.

protected override void Seed(Jobboard.Sandbox.Model.JobboardContext context)
{
    var defaultTemplateGuid = Guid.Parse("xxxxx");
    var defaultTemplate = context.Templates.SingleOrDefault(
        t => t.Guid == defaultTemplateGuid);

    if (defaultTemplate == null)
    {
        context.Templates.Add(
            new Template
                {
                    Guid = defaultTemplateGuid,
                    Name = "Default Template",
                    Content = "Some Default Content"
                });
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top