Last post Mar 30, 2017 02:35 PM by PatriceSc
Mar 30, 2017 01:27 PM|roguenidb|LINK
I am trying to track the changes to i can tell if the entity is new or change but its not working its just adding a new entity to the db.
protected void btnSave_Click(object sender, EventArgs e)
int id = Convert.ToInt32(Request.QueryString["empid"]);
_emp = _solitudeDB.GetEmployeeById(id);
_emp.FirstName = txtFirstName.Text;
_emp.LastName = txtLastName.Text;
_emp.AddressLine1 = txtAddressLine1.Text;
_emp.AddressLine2 = txtAddressLine2.Text;
_emp.Town = txtTown.Text;
_emp.PostCode = txtPostCode.Text;
if (_sol.Entry(_emp).State == System.Data.Entity.EntityState.Detached)
I have included my get code here
public tblEmployee GetEmployeeById(int empId)
tblEmployee _emp = _solitude.tblEmployees.Where(w => w.id == empId).FirstOrDefault();
if (_emp == null)
_emp = new tblEmployee();
Bare in mind I am using ef6 so if this is not the correct way please let me no
Mar 30, 2017 02:35 PM|PatriceSc|LINK
Make sure to call SaveChanges on the same context that you used to retrieve the entity (you have at least _sol vs _solitude so it's perhaps not the same context ?). Exposing the update through _solitudeDB might be better ? Here I suspect that you retrieve
an existing entity on one context, then attach this entity to another context causing saving this entity through this other context to create a new entity.
Not directly related but to me it's better when your code does EXACTLY what you want. Here the same code could either update or create a new employee depending on the id but I'm not sure it's really the best approach. I would likely prefer to make clear
by just reading the code, if I expect to update an employee or to create a new one...