【问题标题】:Inserting EF Code-first seed data only once仅插入一次 EF 代码优先种子数据
【发布时间】:2017-09-13 11:44:06
【问题描述】:

在我的 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);
    }
}

【问题讨论】:

    标签: c# entity-framework-6 code-first


    【解决方案1】:

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

    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) { ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      相关资源
      最近更新 更多