Reputation: 969
I am trying to insert a new record into tblUser
and also update a record in tblEmployee
at the same time. The new record in tblUser saves fine, but the update part of second table is not working.
The complier reads tbEmp.IsUser = true;
this line though. What am I missing.
public void Save(tblUser objUser)
{
MYDB.AddTotblUsers(objUser);
tblEmployee tbEmp = this.GetEmployeeRecordById(objUser.EmpId);
if(tbEmp!=null)
{
string abc = tbEmp.EmployeeCode;
tbEmp.IsUser = true;
}
MYDB.SaveChanges();
}
public tblEmployee GetEmployeeRecordById(Guid gId)
{
return MYDB.tblEmployees.Where(e=>e.EmployeeId == gId).SingleOrDefault();
}
The EmpId is known already and is not necessary that tblUser has to Save First before updating tblEmployee. To make sure, I checked 'abc', I get that employees code there...
Upvotes: 0
Views: 84
Reputation: 709
Try it:
public void Save(tblUser objUser)
{
MYDB.AddTotblUsers(objUser);
MYDB.SaveChanges();
tblEmployee tbEmp = this.GetEmployeeRecordById(objUser.EmpId);
if(tbEmp!=null)
tbEmp.IsUser = true;
}
Obs: You don't have your objUser.EmpID before the insert at database. You need to insert and after it you can get your necessary ID.
if you need to make sure that both are saved or none, use TransactionScope to do it.
public void Save(tblUser objUser)
{
using (TransactionScope ts= new TransactionScope())
{
MYDB.AddTotblUsers(objUser);
MYDB.SaveChanges();
tblEmployee tbEmp = this.GetEmployeeRecordById(objUser.EmpId);
if(tbEmp!=null)
{
tbEmp.IsUser = true;
MYDB.SaveChanges();
}
ts.complete();
}
}
Regards.
Murphy
Upvotes: 1
Reputation: 12616
It's because when you call
tblEmployee tbEmp = this.GetEmployeeRecordById(objUser.EmpId);
it queries your DB (Or at least I think it does, does it? Post the code here.). But your new user is not there yet. It will be added once you call MYDB.SaveChanges();
Upvotes: 1