In my EF code-first MVC application, I am seeding a SuperUser base data. Later on, It's value can be changed from the application interface.
But the problem I am facing - this seed data refreshes every time while I run the application. I don't want this reset. Is there any way to avoid this?
//This is my DatabaseContext.cs -
public partial class DatabaseContext : DbContext
{
public DatabaseContext() : base("name=EntityConnection")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, Migrations.Configuration>());
}
}
//This is my Configuration.cs-
internal sealed class Configuration : DbMigrationsConfiguration<DatabaseContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = false;
}
protected override void Seed(DatabaseContext context)
{
User user = new User()
{
UserId = 1,
EmailAddress = "[email protected]",
LoginPassword = "123",
CurrentBalance = 0,
};
context.Users.AddOrUpdate(user);
}
}
You could just check first if table is empty :
if (!context.Users.Any())
{
User user = new User()
{
UserId = 1,
EmailAddress = "[email protected]",
LoginPassword = "123",
CurrentBalance = 0
};
context.Users.AddOrUpdate(user);
}
Or to see if row with UserId = 1 exist:
if (context.Users.Where(a => UserId == 1).Count() == 0) { ...