ASP.NET MVC应用程序中的实体框架和事务
我有关于在 ASP.NET 应用程序中管理事务的问题。
例如,我有一个计划假期的申请。
控制器有批准假期的表格。
一位用户 - 单击保存并批准休假 ---- 想要休假的员工有 - 1 天 第二个用户 - 单击保存并批准假期,然后?
//pseudocode
public void ApproveVacation(int vacationId)
{
//pull vacationdata from db
var vacation = _dbContext.Vacations.FirstOrDefault(x => x.Id == vacationId);
if (vacation != null && vacation.State != approved) //
{
using (TransactionScope scope = new TransactionScope())
{
vacation.state = approved;
vacation.Employee.Days = -1;
_dbContext.saveChanges();
scope.complete();
}
}
}
问题很简单,对于这种情况来说,事务是否足够,或者我必须使用并发技术之一?
谢谢
编辑:每个请求都会创建一个上下文。
I have question about managing transaction in asp.net application.
For example i have application for planning vacations.
Controller has form to approving vacations.
One user - click save and approve vacation ---- employee which want vacation has - 1 day
second user - clik save and approve vacation and ?
//pseudocode
public void ApproveVacation(int vacationId)
{
//pull vacationdata from db
var vacation = _dbContext.Vacations.FirstOrDefault(x => x.Id == vacationId);
if (vacation != null && vacation.State != approved) //
{
using (TransactionScope scope = new TransactionScope())
{
vacation.state = approved;
vacation.Employee.Days = -1;
_dbContext.saveChanges();
scope.complete();
}
}
}
And question is simple, is transaction enough for this scenario or I must use one of concurency technique?
Thanks
EDIT : Context is created one per request.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事务处理操作的原子性,因此如果操作修改多个数据库记录,它将始终导致一致的状态,其中所有记录都被正确修改(如果操作成功)或所有更改都被回滚(如果操作失败)。
并发处理多个进程/用户对同一记录的可能修改,因为两个进程/用户都可以加载记录的原始版本,但一个可以先保存它,这样当第二个进程尝试保存记录时,它可以默默地覆盖以前的更改。
那么您想在代码中处理什么?
Transaction handles atomicity of the operation so if operation modifies multiple database records it will always result in consistent state where all records are correctly modified (if operation succeeds) or all changes are rolled back (if operation fails).
Concurrency handles possible modification of the same record by multiple processes / users because both could load original version of the record but one could save it first so when the second process tries to save a record it can silently override previous changes.
So what are you trying to handle in your code?
调用“SaveChanges”时您已经有一个隐式事务,因此不需要事务范围。
此外,如果您要更改多个项目,则需要在检索数据之前启动
TransactionScope
。You already have an implicit transaction when calling 'SaveChanges' so there's no need for a transaction scope.
And also, if you would change several items you would need to start the
TransactionScope
before you retrieve the data.