我有这个winforms应用程序,我正在尝试对数据库执行更新。这样做的原因很长,而不是调用简单的验证,结束和更新是因为我想在密码字段上使用自定义方法。 我可以添加记录但不能更新它们。
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");
不会抛出任何错误,但更改/更新的字段不会反映在数据库上。即,更新没有任何反应。
我该如何解决这个问题?
这没什么用。 How can I update a single field from an entity with Entity Framework?
答案 0 :(得分:1)
在entities.SaveChanges();
entities.Entry(userToUpdate).State = EntityState.Modified;
entities.SaveChanges();
编辑1:该错误可能是由于您的Find
查询造成的。您可以在致电SaveChanges()
var entityKey = entities.users.Create().GetType().GetProperty("PrimaryKey_ID").GetValue(userToUpdate); //PrimaryKey_ID is your Identity key of that entity
entities.Entry(entities.Set<users>().Find(entityKey)).CurrentValues.SetValues(userToUpdate);
entities.SaveChanges();