IF you are using Entity framework code first approach, there is a good chance that you will be adding new properties to your modal classes as your development goes further. As we know the “code-first” approach,  creates the database schema from your code ( your classes which represent your entities).  When you add a new property to your class, your tables are not in sync with your classes. because your schema is not updated. So running the project will give you an error like this

The Yellow screen of death while accessing the page in browser.

or while debugging in the IDE

image

What should we need to do to fix this problem ? Lets go back to our example and show what made Visual studio throw me this error.

 

This was my model class

 

public class ContactPerson : Person
{
public virtual ICollection<PhoneNumber> PhoneNumbers { set; get; }

}

 

My ContactPerson class is inherited from the Person class which looks like this

public abstract class Person
{
public int ID { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
public DateTime CreatedDate { set; get; }
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}
}

 

So now I thought of adding a new property to the ContactPerson class so I added a new string property to my class like this

and now my modal class is not in sync with my database. That’s y I got the error when try to run the application.

 

To fix the error, We have to add a new class to our project.I will add this to my DAL folder.

add-new-initializer-class

 

I gave name as “CRMInitializer” and I in herited this class from “DropCreateDatabaseIfModelChanges<CRMContext>”.

My new class has nothing else in that. No methods or no properties or we didn’t even add a constructor

 

Now go to global.asax  and add the below line as the first line in your Application_Start method

 

Database.SetInitializer<OpenMVCRM.DAL.CRMContext>(new DAL.CRMInitializer());

 

So my updated Application_Start looks like this.

 

All set. Entity framework will add a new column to your table now.

Keep in mind that, this approach will drop the existing tables in the database and recreate those tables from scratch. That means you will loose all the data you already stored in the tables.