使用实体中的种子将旧数据移动到新数据库

时间:2018-03-05 17:47:11

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

我希望将我存储的数据从数据库移动到新更改的数据库,因此我使用了种子,但这不起作用,并且没有信息传输到新数据库。

 public class AzmonContext : DbContext
{
    public virtual DbSet<User> Users { get; set; }
    public virtual DbSet<BookGroup> Group { get; set; }
    public AzmonContext()
       : base("default")
    { }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        var sqliteConnectionInitializer = new MyDbContextInitializer(modelBuilder);

        Database.SetInitializer(sqliteConnectionInitializer);
    }
public class MyDbContextInitializer : 
SqliteDropCreateDatabaseWhenModelChanges<AzmonContext>
    {
        public MyDbContextInitializer(DbModelBuilder modelBuilder)
            : base(modelBuilder) { }
protected override void Seed(AzmonContext context)
            {
                using (var db = new AzmonContext())
                {
                    var data = db.Users.ToList();
                    var data2 = db.Group.ToList();
                    foreach (var item in data)
                    {
                        context.Users.Add(new User
                        {
                            Name = item.Name,
                            LName = item.LName,
                            Class = item.Class
                        });
                    }

                    foreach (var item in data2)
                    {
                        context.Group.Add(new BookGroup
                        {
                            GroupName = item.GroupName,
                        });
                    }
                }

                base.Seed(context);
            }
}
}

所以我怎么能这样做?有什么问题吗?

0 个答案:

没有答案