在我的EF代码优先MVC应用程序中,我正在播种SuperUser基础数据。稍后,可以从应用程序界面更改它的值。
但是我面临的问题 - 每次运行应用程序时,此种子数据都会刷新。我不希望这个重置。有什么方法可以避免这种情况吗?
//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);
}
}
答案 0 :(得分:4)
如果表格为空,您可以先检查:
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) { ...