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 Controller 时最终调用的函数。
该功能只是在检查座位可用性后将员工注册到类(class)。大约有200名员工同时报名参加类(class)。
我对每笔交易都使用快照隔离
。
我的问题在于性能。它慢。有时会超时。
我的问题是为什么?我的代码的哪一部分出了问题?所有这些交易中到底发生了什么?什么等待或什么锁定?
最佳答案
您在 for 循环内对数据库进行了多次调用,这意味着您消耗了数据库请求延迟 2 x course.length 倍的总成本,而您应该只需要消耗一次,也许两次。看看是否可以将 db.CourseRegistrations
中的必要数据带出循环,可能作为与类(class)中的数据连接的同一查询的一部分。然后您可以在内存中的循环内执行操作,这将快几个数量级。
关于c# - LINQ to Entities 事务性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34745812/