【发布时间】:2016-06-28 17:12:28
【问题描述】:
我是 EF 的 MVC 新手。我需要在应用程序中实现并发检查。
我正在关注有关 EF 中并发处理的内置支持的 MSDN 帮助:http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application
但就我而言,我正在进行部分更新,因此我使用 AJAX 调用服务器端方法来执行此操作。在这个服务器端方法中,我需要实现并发检查。
按照教程,我对代码进行了必要的更改:
首先在我的数据库中创建了时间戳列:
ALTER TABLE dbo.Job
ADD RowVersion rowversion NULL;
在实体类中:
[Timestamp]
public byte[] RowVersion { get; set; }
在我的映射类中(使用流利的 api):
this.Property(t =>
t.RowVersion).HasColumnName("RowVersion").IsConcurrencyToken();
在我的视图模型类中:
[Timestamp]
public byte[] RowVersion { get; set; }
在我的视图文件中:
@Html.HiddenFor(x => x.RowVersion)
在 JS 文件中(ajax 调用):
function UpdateJobTransferStatus(jobTransferStatusId, newJobTransferSatusId, currentAction, statusName) {
var hdnJobId = $("#JobId").val();
//var hdnRowVersion = $("#RowVersion").val();
var hdnAccountingId = $("#hdnAccountingSystemId").val();
$.ajax(
{
type: "GET",
url: ResolveUrl("~/Api/Job/UpdateJobTransferStatus"),
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { jobId: hdnJobId, currentAction: currentAction, jobTransferStatusId: newJobTransferSatusId, accountingSystemId: hdnAccountingId },//,rowVersion: hdnRowVersion },
success: function (data) {
GetPreviousOrNextStatus(jobTransferStatusId, currentAction, statusName, hdnAccountingId);
},
error: function (result) {
}
});
}
最后在我的控制器中(在我的 ajax 调用中):
我根据 MSDN (using System.Data.Entity.Infrastructure;) 添加了命名空间
[System.Web.Http.HttpGet]
public HttpResponseMessage UpdateJobTransferStatus(int jobId, int currentAction,
int jobTransferStatusId, short accountingSystemId, byte[] rowVersion)
这里我总是得到 'null' 为 'byte[] rowVersion',无论我是否在 AJAX 调用中将值作为参数发送(我一直在我的代码 sn-p 中注释,我贴在这里)。
我已经检查过,每次成功执行插入/更新时,该列都会在数据库中更新,并且视图模型会在每次页面加载时从数据库中获取此 RowVersion 列的最新值。
在 MSDN 示例中,他们已经提交了表单,但我是使用 AJAX 调用来完成的,只是我试图保持每个方面都相同。
发送整个视图模型对象可能会为我完成这项工作,但我不需要整个对象来执行我的部分更新(虽然我没有尝试过)。
如何将rowVersion 传递给 ajax 调用?
【问题讨论】:
-
感谢 Paul,我在提交后立即意识到格式错误,但您比我快得多。 :D
标签: c# ajax asp.net-mvc entity-framework asp.net-mvc-5