Prevent duplicate records with seed

Prevent duplicate records when you use seed method in migration.
Originally in Migrations/Configuration.cs we can use:

context.People.AddOrUpdate(
p => p.FullName,
new Person { FullName = “Andrew Peters” },
new Person { FullName = “Brice Lambson” },
new Person { FullName = “Rowan Miller” }
);

But when we configure adding record (like sample above) every time when we making new migration (add-migration) record are duplicate. In this case need to use:

if (!context.tableModels.Any())
{
var defaultTYP = new List<tableModels>
{
new tableModels{name = “1”, text = “some text”},
new tableModels{name = “2”, text = “some text”},
new tableModels{name = “3”, text = “some text”},
new tableModels{name = “4”, text = “some text”},
};

defaultTYP.ForEach(tableModels => context.tableModels.Add(tableModels));
context.SaveChanges();
}

Leave a Reply

Your email address will not be published. Required fields are marked *