HI all, I have a question about how Entity Framework deals with databases and models, especially when it comes down to change your model after the database has been created.
Let's look at a very simple example. I have an EmployerDetails class as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace input_outputTest.Models
{
public class EmployerDetails
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname{ get; set; }
public int Age { get; set; }
public int EmployerNumber { get; set; }
}
}
Then I create my controller EmployerController the usual way, by selecting the "with a MVC read/write actions and views, using EF" template and using the class as model class and creating a new data context class.
OK now, I run the application and everything's cool. Say that now I want to add another class though, called EmployeeDetails very similar to the above one, like so:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace input_outputTest.Models
{
public class EmployeeDetails
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public int EmployeeNumber { get; set; }
}
}
Now, I presume, I need this data to go on a separate table in the same database, but when I create its own controller the same way as I did for the other class, when I run the application I get an error, saying that "context has changed since the database was created. Consider using Code First Migrations to update the database". From what I read, it's normal to get that error because effectively there is a mismatch between the database and the model - in other word, I seem to understand, the EF database is out of sync with the models. I read about migration, ateempted it but it didn't work, but that's not really the reason for my post, not yet at least: what I want to understand is, how does this new class fit in the EF? Should it sit into a different table or what? SHould it have its own controller, as it has now, or not? Am I getting the structure of the application - any application for that matter not just this - completely wrong? What if I want to add another class at a later date, do I have to go through this hell? I would have thought that migration needed to be done only if you changed a model, not if you added another one: for example, take the first class: if I add an extra field, something like
public string Position{get; set;}
then migration must be enabled because the table is missing that new field, but evindetly it's not like that.
Can somebody clarify please and then if the solution is to enable migration I will let you know what I've done and hopefully we can understand why the database isn't updating.
thanks