问题
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