下面的代码是从Wep v4脚手架工具生成的。
放置法
public IHttpActionResult Put([FromODataUri] string key, Delta<Product> patch)
{
Validate(patch.GetEntity());
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Product product = db.Products.Find(key);
if (product == null)
{
return NotFound();
}
patch.Put(product);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(product);
}贴片法:
[AcceptVerbs("PATCH", "MERGE")]
public IHttpActionResult Patch([FromODataUri] string key, Delta<Product> patch)
{
Validate(patch.GetEntity());
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Product product = db.Products.Find(key);
if (product == null)
{
return NotFound();
}
patch.Patch(product);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(product);
}中的Rowversion字段
[Timestamp]
public byte[] RowVersion { get; set; }问题:
DbUpdateConcurrencyException从未抛出。有什么原因吗?[ConcurrencyCheck]的属性,它的用途是什么?我能用这个吗?提供代码示例将是非常感谢的!
发布于 2016-06-07 21:20:54
我解决了这个问题,检查我自己的并发字段,因为补丁或put做不到。这是我的代码,plato.TimeStamp是[Timestamp]属性。
public async Task<IHttpActionResult> Put([FromODataUri] int key, Delta<Plato> patch)
{
Validate(patch.GetEntity());
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Plato plato = await db.Platos.FindAsync(key);
if (plato == null)
{
return NotFound();
}
//Here save the current value in the DB
string timeStamp = Convert.ToBase64String(plato.TimeStamp);
patch.Put(plato);
try
{
//Here plato.TimeStamp is update from remote, must be equal to stored value
if (timeStamp != Convert.ToBase64String(plato.TimeStamp))
{
throw new DbUpdateConcurrencyException();
}
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PlatoExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(plato);
}https://stackoverflow.com/questions/37475442
复制相似问题