I have this winforms application where I am trying to perform an update to a database. The reason for doing it my long way instead of calling the simple validate, endedit and update is that I want to use a custom method on the password field. I am able to add records but not update them.
var users = entities.users.AsEnumerable().Where(x => x.Code.Equals(int.Parse(txtUsersCode.Text))).FirstOrDefault();
if (users == null)
{
user userToAdd = new user
{
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_payroll_enterpriseEntities ctx = new eko_payroll_enterpriseEntities())
{
var userToUpdate = ctx.users.Find(users.Code);
if (userToUpdate != null)
{
//entities.Configuration.ValidateOnSaveEnabled = false;
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;
entities.SaveChanges();
}
}
}
MessageBox.Show("User details updated successfully");
No error is thrown but the changed/updated fields do not reflect on the database. I.e, nothing happens on update.
How do I fix this?
This didn't help much. How can I update a single field from an entity with Entity Framework?