在我的ef代码优先应用程序中,我正在播种超级用户基础数据。稍后,它的值可以从应用程序接口更改。
但是我面临的问题 - 每次运行应用程序时,此种子数据每次都会刷新。我不想要这个重置。有什么办法避免这种情况吗?
//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);
}
}
您可以先检查表是否为空:
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) { ...