Click here to Skip to main content
15,881,027 members
Articles / Database Development / MySQL
Tip/Trick

Custom Adding/Updating using Entity Framework 5

Rate me:
Please Sign up or sign in to vote.
4.55/5 (4 votes)
28 Mar 2014CPOL 8.6K   4  
Being able to add or update data field by field through Winforms using EF5, .NET 4.5

Introduction

Entity Framework is useful as an easy way for a developer to access, add, update and delete data for an application.

A developer can have a form with multiple fields and by calling code such as:

C#
private void usersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
       {
           try
           {
               this.Validate();
               this.usersBindingSource.EndEdit();

               this.usersTableAdapter.Update(this.eko_payrollDataSet.users);
               this.eko_payrollDataSet.users.AcceptChanges();
               this.usersTableAdapter.Fill(this.eko_payrollDataSet.users);

               MessageBox.Show("User details updated successfully");
           }
           catch (System.Exception ex)
           {
               System.Windows.Forms.MessageBox.Show(ex.Message);
           }
       }

He/she can easily be able to add this under the save button of the Windows nav bar for databound data.

Background

However, a developer may sometimes want to manipulate data for a certain field before adding or updating it to the database. E.g., hashing and encrypting a password before storage in a database.

Using the Code

The code below can be used for any other purpose apart from what is shown. It can be edited to suit a developers needs. Used when a user clicks on the navigation save button, the database will be changed accordingly either for adding or updating data.

GlobalClass.HashEncrypt is a method used on the password field.

C++
private void usersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            try
            {
                var users = entities.users.AsEnumerable().Where(x => x.Code.Equals(int.Parse(txtUsersCode.Text))).FirstOrDefault();

                if (users == null)
                {
                    user userToAdd = new user     // for adding
                    {
                        firstName = txtUsersFName.Text,
                        lastName = txtUsersLName.Text,
                        username = txtUsersUName.Text,
                        password = GlobalClass.HashEncrypt(txtUsersPassword.Text),
                        created = DateTime.Now,
                        companyAllocated = companyAllocatedComboBox.Text
                    };

                    entities.users.Add(userToAdd);
                    entities.SaveChanges();
                    this.usersTableAdapter.Fill(this.eko_payrollDataSet.users);
                }
                else   
                {
                    using (eko_enterpriseEntities ctx = new eko_enterpriseEntities())
                    {
                        var userToUpdate = ctx.users.Find(users.Code);

                        if (userToUpdate != null)   // for updating
                        {
                            userToUpdate.firstName = txtUsersFName.Text;
                            userToUpdate.lastName = txtUsersLName.Text;
                            userToUpdate.username = txtUsersUName.Text;
                            userToUpdate.password = GlobalClass.HashEncrypt(txtUsersPassword.Text);
                            userToUpdate.modified = DateTime.Now;
                            userToUpdate.companyAllocated = companyAllocatedComboBox.Text;

                            if (entities.Entry(userToUpdate).State == EntityState.Detached)
                            {
                                var entityKey = entities.users.Create().GetType().GetProperty("Code").GetValue(userToUpdate);
                                entities.Entry(entities.Set<user>().Find(entityKey)).CurrentValues.SetValues(userToUpdate);
                                entities.SaveChanges();
                                this.usersTableAdapter.Fill(this.eko_payrollDataSet.users);
                            }
                        }
                    }
                }
                MessageBox.Show("User details updated successfully");                
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }

Points of Interest

I came up with this form after reading a few developer forum websites. Hope it may be of help to some.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) GetNet
Kenya Kenya
http://www.kinyanjuikamau.com

Comments and Discussions

 
-- There are no messages in this forum --