Why doesn't DropCreateDatabaseAlways drop the database when the model changes?

喜你入骨 提交于 2019-12-11 06:37:58

问题


I have a model with one entity:

   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; }
    }

}

The Initializer class:

 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();
        }
    }

Main Method:

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();
        }

To understand the role of DropCreateDatabaseAlways I deleted a property from this entity(Blog), and when I run the application, it throws this error:

There is already an object named 'Blogs' in the database.

Shouldn't it drop the database at any case, and then recreate it from the presented model?

来源:https://stackoverflow.com/questions/39551770/why-doesnt-dropcreatedatabasealways-drop-the-database-when-the-model-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!