ASP MVC代码优先更新模型而不会丢失数据

时间:2019-05-15 07:00:04

标签: sql-server asp.net-mvc entity-framework

我有以下DbContext

namespace Tasks.Models
{
    public class TaskDBInitializer :  DropCreateDatabaseIfModelChanges<TasksContext>
    {
        protected override void Seed(TasksContext context)
        {
            var projects = new List<Projects>
            {
                new Projects{ Title="proTitle", Describe="proDescribe" },
            };
            projects.ForEach(p => context.Projects.Add(p));
            context.SaveChanges();
            base.Seed(context);;
        }
    }

    public class TasksContext : DbContext
    {
        public TasksContext() : base("name=TaskDB")
        {
            Database.SetInitializer(new TaskDBInitializer());
        }
        public DbSet<Task> Task { get; set; }
        public DbSet<Projects> Projects { set; get; }
    }
}

我现在想添加另一个模型,但是不想丢失当前数据库中存在的数据。

如何在不丢失数据的情况下向我的DbContext添加模型?

1 个答案:

答案 0 :(得分:1)

使用MigrateDatabaseToLatestVersion<TContext,TMigrationsConfiguration>代替DropCreateDatabaseIfModelChanges<TContext>作为IDatabaseInitializer<TContext>来确定DbContext中的更改,然后更新现有数据库以使其兼容。

以下是如何实现MigrateDatabaseToLatestVersion初始化程序的示例:

namespace Tasks.Models
{
    public sealed class TaskDBConfiguration : DbMigrationsConfiguration<TasksContext>
    {
        public TaskDBConfiguration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = false;
        }

        protected override void Seed(TasksContext context)
        {
            var projects = new List<Projects>
            {
                new Projects { Title = "proTitle", Describe = "proDescribe" },
            };

            projects.ForEach(p => context.Projects.Add(p));

            context.SaveChanges();

            base.Seed(context);
        }
    }

    public class TasksContext : DbContext
    {
        public TasksContext() : base("name=TaskDB")
        {
            Database.SetInitializer<TasksContext>(
              new MigrateDatabaseToLatestVersion<TasksContext, TaskDBConfiguration>()
            );
        }

        public DbSet<Task> Task { get; set; }
        public DbSet<Projects> Projects { set; get; }
    }
}