插入一次EF代码优先种子数据
作者:互联网
在我的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);
}
}
解决方法:
您可以先检查表是否为空:
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) { ...
标签:entity-framework-6,code-first,c 来源: https://codeday.me/bug/20191025/1930631.html