|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Transactions;
namespace EFTransactionExample.Models
{
class ApplicationModel
{
// Get all the information for the employees
public IEnumerable<Employee> GetEmployeeInformation()
{
EmployeeSalaryEntities context = new EmployeeSalaryEntities();
return context.Employees.AsEnumerable<Employee>();
}
// Set an employee's salary to a value
public void SetEmployeeSalary(int employeeID,
string employeeName, int salary)
{
EmployeeSalaryEntities context = new EmployeeSalaryEntities();
var employee = context.Employees.Where(e => e.ID == employeeID)
.SingleOrDefault<Employee>();
if (employee == null)
{
employee = new Employee()
{
ID = employeeID,
Name = employeeName,
Salary = salary
};
context.Employees.AddObject(employee);
}
employee.Salary = salary;
context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
}
public void RaiseEmployeeSalaryNonSerialized(int employeeID, int amount)
{
// Read employee information
EmployeeSalaryEntities context = new EmployeeSalaryEntities();
var employee = context.Employees.Where(e => e.ID == employeeID)
.Single<Employee>();
// sleep a while
System.Threading.Thread.Sleep(5000);
// Update the salary
employee.Salary = employee.Salary + amount;
context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
}
public void RaiseEmployeeSalarySerialized(int employeeID, int amount)
{
TransactionOptions options = new TransactionOptions();
options.IsolationLevel = IsolationLevel.Serializable;
using (TransactionScope scope
= new TransactionScope(TransactionScopeOption.Required, options))
using (EmployeeSalaryEntities context = new EmployeeSalaryEntities())
{
// Open the database connection explicitly
context.Connection.Open();
// Read employee information
var employee = context.Employees.Where(e => e.ID == employeeID)
.Single<Employee>();
// sleep a while
System.Threading.Thread.Sleep(5000);
// Update the salary
employee.Salary = employee.Salary + amount;
context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
scope.Complete();
}
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
I have been working in the IT industry for some time. It is still exciting and I am still learning. I am a happy and honest person, and I want to be your friend.