Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Custom Adding/Updating using Entity Framework 5

0.00/5 (No votes)
28 Mar 2014 1  
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:

 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.

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here