仅插入一次 EF 代码优先种子数据

Inserting EF Code-first seed data only once

在我的 EF 代码优先 MVC 应用程序中,我正在播种超级用户基础数据。稍后,可以从应用程序界面更改它的值。

但我面临的问题是,每次 运行 应用程序时,种子数据都会刷新。我不想要这个重置。有什么办法可以避免这种情况吗?

//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);
    }
}

您可以先检查 table 是否为空:

if (!context.Users.Any())
{
    User user = new User()
    {
        UserId = 1,
        EmailAddress = "xyz@abc.com",
        LoginPassword = "123",
        CurrentBalance = 0
    };
    context.Users.AddOrUpdate(user);
}

或者查看 UserId = 1 的行是否存在:

if (context.Users.Where(a => UserId == 1).Count() == 0) { ...