DropCreateDatabaseAlways为什么不在模型更改时删除数据库?

时间:2016-09-17 21:07:41

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

我有一个带有一个实体的模型:

   namespace TestMigration
{
    public class BlogContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
        public int FollowersCount { get; set; }
        //public int BloggerAge { get; set; }
    }

}

Initializer类:

 public class DataInitializer : DropCreateDatabaseAlways<BlogContext>
    {
        protected override void Seed(BlogContext context)
        {
            var blogs = new List<Blog>
            {
                new Blog {FollowersCount=456, Name="ABC", Url="abc.com" },
                new Blog {FollowersCount=789, Name="DEF", Url="def.com" },
                new Blog {FollowersCount=246, Name="GHI", Url="ghi.com" },
                new Blog {FollowersCount=135, Name="JKL", Url="jkl.com" },
                new Blog {FollowersCount=258, Name="MNO", Url="mno.com" }
            };
            blogs.ForEach(b => context.Blogs.Add(b));
            context.SaveChanges();
        }
    }

主要方法:

static void Main(string[] args)
        {

            Database.SetInitializer(new DataInitializer());
            using (var db = new BlogContext())
            {
                //db.Blogs.Add(new Blog { Name = "KOLP" });
                //db.SaveChanges();
                foreach (var blog in db.Blogs)
                {
                    Console.WriteLine($"\n*****({blog.BlogId})*****");
                    Console.WriteLine("blog.Name: " + blog.Name);
                }
            }
            Console.ReadLine();
        }

要了解DropCreateDatabaseAlways我从此实体(Blog)删除了一个属性的角色,当我运行该应用程序时,它会抛出此错误:

  

数据库中已有一个名为“博客”的对象。

在任何情况下都不应该丢弃数据库,然后从呈现的模型中重新创建它?

0 个答案:

没有答案