HI i have this update query which works fine but just it takes about 3-4 seconds before i get the messagebox update successfully. Could you help to see what goes wrong? Is it because of the using() and the transaction rollback?
public void Update()
{
Syst开发者_C百科em.Data.Common.DbTransaction transaction = null;
using (JamminDataContext db = new JamminDataContext())
{
try
{
db.Connection.Open();
transaction = db.Connection.BeginTransaction();
db.Transaction = transaction;
#region Update Users
db.Users.Attach(this, GetSingleUserById(this.Id));
db.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, db.Users);
db.SubmitChanges();
#endregion
if (this.RoleId == (int)RoleTypes.Student)
{
#region Update CourseByStudents
foreach (CourseByStudent courseByStudent in this.courseByStudent)
{
if (courseByStudent == null) break;
if (courseByStudent.Id == 0)
{
courseByStudent.CourseUserStatus.UserId = this.Id;
db.CourseUserStatus.InsertOnSubmit(courseByStudent.CourseUserStatus);
db.SubmitChanges();
courseByStudent.StudentId = this.Id;
courseByStudent.CourseUserStatusId = courseByStudent.CourseUserStatus.Id;
db.CourseByStudents.InsertOnSubmit(courseByStudent);
db.SubmitChanges();
}
else
{
if(courseByStudent.CourseUserStatusCopy != courseByStudent.CourseUserStatus.Status
&& ( courseByStudent.CourseUserStatus.Status != null
&& courseByStudent.CourseUserStatus.Date != null))
{
//Insert to CourseUserStatus only when Status is change or add new row of course
courseByStudent.CourseUserStatus.UserId = this.Id;
db.CourseUserStatus.InsertOnSubmit(courseByStudent.CourseUserStatus);
db.SubmitChanges();
courseByStudent.CourseUserStatusId = courseByStudent.CourseUserStatus.Id;
}
courseByStudent.Update();
}
}
#endregion
}
transaction.Commit();
}
catch (Exception ex)
{
if (transaction != null) transaction.Rollback();
Logger.Error(typeof(User), ex);
throw;
}
finally
{
if (db.Connection.State == System.Data.ConnectionState.Open) db.Connection.Close();
}
}
}
Instead of doing all the individual db.SubmitChanges() make one call to db.SubmitChanges() right before the tx.Commit(). Let me know if this improves performance. It should prevent many roundtrips to the database and thus improve the overall performance.
精彩评论