Whenever I navigate to a particular page and then leave it some tables are deleted. The only thing that differs between this page and the rest is that this page uses a different DbContext. The tables deleted are also part of a different DbContext which is not used on the page visited. This has really got me, any suggestions?
The controller that crashes the page is.
public class GenerationController : Controller
{
private GenerationDbContext GenerationDb = new GenerationDbContext();
private string generatedDir = "~/App_Data/Generated";
//
// GET: /Generation/
public ViewResult Index()
{
var viewModel = new GenerationIndexViewModel
{
Generations = GenerationDb.Generations
.OrderByDescending(g => g.GeneratedOn)
.ToList()
};
return View(viewModel);
}
protected override void Dispose(bool disposing)
{
GenerationDb.Dispose();
base.Dispose(disposing);
}
}
UPDATE: I just realized I have another page that accesses both DbContexts. For some reason, I can navigate to this page and then leave without deleting tables. It is just this one page that deletes all the tables for the other context.
UPDATE: When I change the Index action to.
public ActionResult Index()
{
return Content("Hello.");
}
I can navigate between the page and all the other pages fine. No errors about tables being deleted. Ergo, I’m positive it has to do something with the model or database context. Which are so.
public class Generation
{
public int Id { get; set; }
[Required]
public DateTime GeneratedOn { get; set; }
[Required, StringLength(4000)]
public string Name { get; set; }
}
public class GenerationDbContext : DbContext
{
public DbSet<Generation> Generations { get; set; }
}
UPDATE: Using the Database Explorer provided with VWD, there is the Generations table when I navigate to the page. And when I navigate to another page that use a different database context, the Generations table is still the only table. Argh!
Sounds like you have Code First; the first time each dbcontext runs, it checks the database it is configured to connect to. If the schema is not what it expects to find, it flattens the database and recreates tables based on the model classes used by that context.
There are numerous paths to solve this. The easiest are to combine your contexts, or direct each one to its own separate database.