LINQ Transaction
System.Data.Common.DbTransaction trans =
null;
DataClassesDataContext objDataClass =
new
DataClassesDataContext
(ConfigurationManager.ConnectionStrings
[Constants.ConnectionString].ConnectionString);
try
{
// Nullable data type as the methods
generated for SP will use Nullable
// type
int? intCategoryID =0;
int? intProductID =0;
// Open the connection
objDataClass.Connection.Open();
// Begin the transaction
trans = objDataClass.Connection.BeginTransaction();
// Assign transaction to context class
// All the database operation perform by this object will now use
//transaction
objDataClass.Transaction = trans;
// Insert Category
// I have to use Ref keyword CategoryID of newly added category will
// be assign to this variable
objDataClass.InsertCategory
(
ref
intCategoryID,
txtName.Text.Trim().Replace(“‘”,
“””),
txtDescription.Text.Trim().Replace(“‘”, “””),
new byte[0]
);
// Insert Product
// I have to use Ref keyword as ProductID of newly generated product will
// be assign to this variable
objDataClass.InsertProduct
(
ref
intProductID,
txtProductName.Text.Trim().Replace(“‘”,“””),
null,
intCategoryID,
txtQuantityPerUnit.Text.Trim().Replace(“‘”,
“””),
Convert.ToDecimal(
txtUnitPrice.Text.Trim().Replace(“‘”,
“””)
),
null,
null,
null,
0);
// Commit transaction
trans.Commit();
}
catch (Exception
ex)
{
// Rollback transaction
if (trans != null)
trans.Rollback();
}
finally
{
//
Close the connection
if
(objDataClass.Connection.State == ConnectionState.Open)
objDataClass.Connection.Close();
}