【发布时间】:2014-03-26 11:59:24
【问题描述】:
使用 EntityFramework v6,我正在组合一个原型来演示 Web Api 以及桌面应用程序中的并发检查。
实体:
public static class IRowVersionExtensions
{
public static string RowVersionAsString(this IRowVersion ivr)
{
return Convert.ToBase64String(ivr.RowVersion);
}
public static void SetRowVersion(this IRowVersion ivr, string rowVersion)
{
ivr.RowVersion = Convert.FromBase64String(rowVersion);
}
}
public interface IRowVersion
{
byte[] RowVersion { get; set; }
}
public class Department : IRowVersion
{
[Key]
public int Id { get; set; }
[Required, MaxLength(255)]
public string Name { get; set; }
public string Description { get; set; }
[Timestamp]
[ConcurrencyCheck]
public byte[] RowVersion { get; set; }
}
数据库上下文:
public class CompDbContext : DbContextEx
{
public CompDbContext()
: base("Company")
{
this.Configuration.LazyLoadingEnabled = false;
}
public DbSet<Department> Departments { get; set; }
}
桌面应用程序(控制台应用程序)具有以下代码,并按预期抛出 DbConcurrencyException:http://pastebin.com/i6yAmVGc
现在,API 控制器 - 当我在两个窗口中打开页面并编辑一个(并保存)然后尝试编辑/保存另一个时,它不会引发异常:
Api 控制器更新操作:
[HttpPatch, Route("")]
public Department UpdateDepartment(Department changed)
{
var original = dbContext.Departments.Find(changed.Id);
if (original == null)
this.NotFound();
if (Convert.ToBase64String(changed.RowVersion) != Convert.ToBase64String(original.RowVersion))
Console.WriteLine("Should error.");
original.RowVersion = changed.RowVersion;
original.Name = changed.Name;
original.Description = changed.Description;
dbContext.SaveChanges();
return original;
}
API 调用:
DepartmentVM.prototype.onSave = function (entity) {
var method = entity.id() ? 'PATCH' : 'PUT';
$.ajax({
url: '/api/departments',
method: method,
data: ko.toJSON(entity),
contentType: 'application/json',
dataType: 'JSON'
})
.done(function (data) {
alert('Saved');
entity.rowVersion(data.rowVersion);
entity.id(data.id);
})
.error(function (data) {
alert('Unable to save changes to department.');
});
};
当我在控制器动作中断线时:
if (Convert.ToBase64String(changed.RowVersion) != Convert.ToBase64String(original.RowVersion))
第一次保存时,changed.RowVersion == original.RowVersion(完美)并保存(如预期的那样)。在第二页的保存中,changed.RowVersion != original.RowVersion(完美)但它仍然保存,没有异常(不符合预期)。
谁能帮我理解为什么这在桌面应用程序中工作得很好,但在 Web API 中却不行?
【问题讨论】:
-
您的问题标题中不必填写
[SOLVED]。您在下面的答案上打的绿色复选标记向系统(以及所有其他感兴趣的用户)表明该问题已“解决”。 -
啊,没意识到 - 谢谢。
标签: asp.net-mvc entity-framework knockout.js concurrency