How to Use transaction.
When we want to save data to multiple table or in multiple time in a table use transaction.
follow code snip below.
Class Abc {
//Object Declaration
ProjectRepository pr = new
ProjectRepository();
DBDataContext DBObject = new DBDataContext();
//Action
public ActionResult
FormEntry(FormCollection fc)
{
System.Data.Common.DbTransaction Tran=null;
DBObject.Connection.Open();
Tran =
DBObject.Connection.BeginTransaction();
DBObject.Transaction = Tran;
try
{
//---Code of insert or Update---
DataTable dtc = (DataTable)SessionBag.Current.ChequeDetailsXV;
if (dtc.Rows.Count > 0)
{
foreach (DataRow dr in dtc.Rows)
{
CapitalDetail Pc = new
CapitalDetail();
Pc.PrGroup_ID = Convert.ToInt32(dr["PrGroup_ID"]);
Pc.Capi_Amount = Convert.ToInt32(dr["Amount"]);
Pc.Capi_Bank = Convert.ToString(dr["ChqBankBranch"]);
Pc.Capi_Bank_Branch
= Convert.ToString(dr["ChqBankBranch"]);
//Pc.Capi_OutStation =
Convert.ToString(dr["DrawNo"]);
Pc.Capi_ChequeNo = Convert.ToInt32(dr["ChqNo"]);
Pc.Capi_Date = Convert.ToDateTime(dr["ChqDate"]);
Pc.Capi_EntryDate =
Convert.ToDateTime(DateTime.Now);
Pc.Capi_Type = Convert.ToString("Cheque");
pr.Add(Pc);
}
}
pr.Save();
Tran.Commit();
}
catch (Exception ex)
{
Tran.Rollback();
}
finally
{
if
(DBObject.Connection != null &&
DBObject.Connection.State == System.Data.ConnectionState.Open)
{
DBObject.Connection.Close();
}
}
}
nice
ReplyDelete