Model First Development Using EF 5.0 – Updating the Model

In my earlier post, Getting started with Model First development using EF, I have shown you to create a database from the model class and how to persist the data to the database. In the second part of the series, I am going to show how the changes made to the underlying database can be reflected in the model class.

 

So let’s try to add a column to our user table.

ALTER TABLE MT_USER
ADD Gender Varchar(5)

 

Now right click inside the EDMX designer to bring up the pop menu and select Update Model from the database option to reflect the changes we made to the database.

 

 

 

In the Update Wizard dialog, all the newly added columns or views or stored procedures will be listed under Add tab, whereas the Refresh tab will all the modified ones. Just click on the finish button to start the update operation.

 

 

 

Once the operation is completed our designer will show the newly added class and also will automatically updates the auto-generated code to reflect the changes made to the model

 

 

 

Let’s write some code to show our changes to the model in action

            using (var db = new EFModelFirstContainer())
            {
                try
                {
                    var user = db.MT_USER.Create();

                    user.GroupCode = "Admin";
                    user.Username = "dev";
                    user.FirstName = "Dev";
                    user.LastName = "Amal";
                    user.Gender = "male";
                    db.MT_USER.Add(user);
                    db.SaveChanges();

                }

                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        }
                    }
                }
  }

 

And here’s the result and you can see the second row with data in the Gender colum.

 

 


No Comments

Add a Comment