【发布时间】:2016-04-17 04:40:49
【问题描述】:
public void Register(decimal groupId, decimal deptId, decimal employeeId)
{
using (EmployeeEntities db = new EmployeeEntities())
{
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Snapshot }))
{
var course = db.Courses.Where(s => s.GroupId == groupId && s.DepartmentId == deptId).ToList();
foreach (var item in course)
{
var filledSeats = db.CourseRegistrations.Count(c => c.CourseId == item.CourseId && c.DepartmentId == deptId && (c.CancelledFl == null || c.CancelledFl == false));
if (item.AllotedSeats <= filledSeats)
{
throw new Exception("Sorry! Seats are not available for " + db.Groups.Where(s => s.GroupId == item.GroupId).Select(s => s.GroupName).FirstOrDefault());
}
if (!db.CourseRegistrations.Any(s => s.EmployeeId == employeeId && s.CourseId == item.CourseId && (s.CancelledFl == false || s.CancelledFl == null)))
{
var courseRegister = new CourseRegistration();
db.CourseRegistrations.Add(courseRegister);
courseRegister.CourseId = item.CourseId;
courseRegister.EmployeeId = employeeId;
courseRegister.CreatedBy = 1;
courseRegister.CreatedDt = DateTime.Now;
courseRegister.RecordVa = 1;
item.FilledSeats = item.FilledSeats + 1;
}
}
db.SaveChanges();
scope.Complete();
}
}
}
考虑上面的代码。当请求发送到ASP.NET WebAPI 控制器时,它最终会被调用。
该功能只是在检查座位可用性后将员工注册到课程。大约 200 名员工将同时注册课程。
我在每笔交易中都使用Snapshot Isolation。
我的问题在于性能。这是慢。有时会超时。
我的问题是为什么?我的代码的哪一部分出错了?所有这些交易中到底发生了什么?什么等待或什么锁定?
【问题讨论】:
标签: c# sql-server performance entity-framework asp.net-web-api