10

我将 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
    }

}

谢谢,

4

2 回答 2

17

以下是仅通过在种子方法中提供 .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);
    }
}
于 2012-10-16T08:27:35.090 回答
0

基于代码的迁移是模型更改后现有数据库(手动数据库更新)的推荐方法。您可以在包命令行窗口中通过 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
    }

}
于 2013-08-29T18:02:42.130 回答