Model Changes in Code First Approach

In our previous example we work on code first approach with relationships. In this article I want to explain the changes of model in code first approach. After creating database using code-first-api if we need to change like addition of new column, data type of previous column etc.

Suppose we have following class

public class employee
{
    [Key]
    public int emp_id { get; set; }
    public string name { get; set; }
    public int age { get; set; }

    public int salary { get; set; }

  }

		

If I am having requirement, I want to add lname column in this class.

public class employee
{
    [Key]
    public int emp_id { get; set; }
    public string name { get; set; }
    public int age { get; set; }

    public int salary { get; set; }

    public string lname { get; set; }
}

		

So it will generate following error

changes in model class in EF

		Figure 1
		

Migration history has been changed so it will generate error. To remove this error we need to add global application file in our project

And in application_start add following code

void Application_Start(object sender, EventArgs e)
    {
        System.Data.Entity.Database.SetInitializer
            (new System.Data.Entity.DropCreateDatabaseIfModelChanges<efRepositary>());
        

    }

		

Now again execute the code and your changes will be done.

Note: - complete data will be lost in this way.


Email Address

For any query you can send mail at info@techaltum.com
Thanks