【问题标题】:EF 5 Code First Migration Bulk SQL Data SeedingEF 5 Code First 迁移批量 SQL 数据播种
【发布时间】:2012-10-15 22:01:20
【问题描述】:

我将 EF5 与 MVC4 一起使用。问题是我的数据库中有大量数据,我已经从旧数据库中导入了这些数据。我想在模型更改时加载该数据的种子。 我的问题是如何播种数据库中已经存在的大量数据?

internal sealed class Configuration : MigrationsConfiguration<VoiceLab.Models.EFDataContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(VoiceLab.Models.EFDataContext context)
    {
     //what to do here to seed thousands or records that are already in db
    }

}

谢谢,

【问题讨论】:

    标签: entity-framework ef-code-first entity-framework-migrations


    【解决方案1】:

    您可以通过在种子方法中提供 .sql 文件来为批量数据播种。

    public class AppContextInitializer : CreateDatabaseIfNotExists<AppContext>
    {
        protected override void Seed(AppContext context)
        {
            var sqlFiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.sql").OrderBy(x => x);
            foreach (string file in sqlFiles)
            {
                context.Database.ExecuteSqlCommand(File.ReadAllText(file));
            }
    
            base.Seed(context);
        }
    }
    

    【讨论】:

    【解决方案2】:

    基于代码的迁移是模型更改后现有数据库(手动数据库更新)的推荐方法。您可以在包命令行窗口中通过 PowerShell 执行此操作。这样,现有数据将被保留。

    如果您是使用源代码控制的开发人员团队的一员,您应该使用纯自动迁移或纯基于代码的迁移。考虑到在团队环境中使用基于代码的迁移进行自动迁移的局限性,建议使用。

    http://msdn.microsoft.com/en-us/data/jj591621

    http://elegantcode.com/2012/04/12/entity-framework-migrations-tips/

    internal sealed class Configuration : MigrationsConfiguration<DataContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
    
            // if model changes involve data lose
            AutomaticMigrationDataLossAllowed = true;
    
        }
    
        protected override void Seed(DataContext context)
        {
         //seed only when creating or new database
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 2014-10-08
      • 1970-01-01
      • 2020-12-03
      相关资源
      最近更新 更多