[英]Updating database fields with Entity Framework 5
I have this winforms application where I am trying to perform an update to a database. 我有一个Winforms应用程序,在其中尝试对数据库执行更新。 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. 我之所以这样做是因为我想在密码字段上使用自定义方法,而不是调用简单的validate,endedit和update。 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. 不会引发任何错误,但是更改/更新的字段不会反映在数据库上。 Ie, 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? 如何使用Entity Framework更新来自实体的单个字段?
Add this before entities.SaveChanges();
将此添加到entities.SaveChanges();
之前entities.SaveChanges();
entities.Entry(userToUpdate).State = EntityState.Modified;
entities.SaveChanges();
Edit 1: That error may be due to your Find
query. 编辑1:该错误可能是由于您的Find
查询。 You can try doing this before Calling SaveChanges()
您可以在调用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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.