2016-03-29 15 views
1

如果我运行在包管理器控制台下面的代码:实体Framwork的Code First迁移

-Update-Database -Force 

除了运行一些默认的数据表,我还以为所有的表被清洁的种子法之前,但这似乎是不正确的!?

编辑:

我还是觉得很奇怪,为什么在数据库中的表,当我运行-update数据库-force没有DROP掉,如果他们不这样做呢?为什么每次运行-update-database时,使用Seed方法添加的数据都会继续添加数据。再次,不应该prevoius添加的数据被覆盖?当我从ASP.NET这个链接和其他来源阅读下面的文本看起来应该有可能用新数据播种,旧数据或表应该被丢弃!?我是否误解了这一点,或者我做错了什么?

You have configured the Entity Framework to automatically drop and 
re-create the database each time you change the data model. When you 
add, remove, or change entity classes or change your DbContext class, 
the next time you run the application it automatically deletes your 
existing database, creates a new one that matches the model, and seeds 
it with test data. 
+0

如果你删除数据库,你应该有一个初始化程序集来创建一个新的程序 – Ortund

+0

@Ortund我是ASP.NET MVC的新手,在研究过程中的以前的项目中,我记得刚刚删除了DB,然后键入一些命令或它是由Visual Studio创建的,但我可能是错的?你是什​​么意思与初始化? –

+0

我会在一个答案中解释,但你不需要接受它,除非它工作 – Ortund

回答

2

使用实体框架代码首先,你可以有你的MVC项目中删除,并且当它运行使用Database Initializers重新创建数据库。

//Global.asax.cs 
    protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 
     GlobalConfiguration.Configure(WebApiConfig.Register); 
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 

     // instanciate your DbContext class 
     OrtundEntities db = new OrtundEntities(); 
     db.Database.Initialize(true); // this calls your chosen initializer 
     db.Seed(); 
    } 

// OrtundEntities 
    public OrtundEntities() 
     : base("DefaultConnection") 
    { 
     Database.SetInitializer<OrtundEntities>(DropCreateDatabaseAlways); 
    } 

这将始终删除并创建数据库在运行MVC的网站(我相信只要用户访问它,以及因此只能使用DropCreateDatabaseAlways用于测试目的)。

或者,如果只有一个或两个表需要清空,以下内容在您的控制器中可以正常工作。这有利于保持所有其他数据的完整性,并只清空要清空的表格。

public JsonResult ClearAll() 
    { 
     try 
     { 
      // clears the Receipts and Rewards tables 
      db.Database.ExecuteSqlCommand("truncate table Receipts"); 
      db.Database.ExecuteSqlCommand("truncate table Rewards"); 

      return Json(true, JsonRequestBehavior.AllowGet); 
     } 
     catch (Exception ex) 
     { 
      return Json(ex.Message, JsonRequestBehavior.AllowGet); 
     } 
    } 

编辑

我忘了提,如果你用上面的函数截断表具有关系型数据,其他表的依赖那么任何查询这些表很可能会导致错误。

+0

感谢您的答案!我将在稍后尝试代码 –