简体   繁体   中英

Inserting EF Code-first seed data only once

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 = "xyz@abc.com",
                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 = "xyz@abc.com",
        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) { ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM