我正在ASP.NET Core 2.0上的Web api项目上工作,其中Entity Framework Core连接到了postgres数据库。以下PUT方法可以正常工作,但我觉得我可能误会了update方法的使用,而且我还觉得应该有一个更优雅的解决方案,以一种持有PUT请求(而不是PATCH)的方式更新现有对象)。 // PUT: api/Discount/5 [HttpPut("{id}")] [ProducesResponseType(204)] [ProducesResponseType(400)] [ProducesResponseType(404)] [ProducesResponseType(500)] public IActionResult Put(int id, [FromBody]Discount discount) { if (ModelState.IsValid) { using (var context = new BarberskabetDbContext()) { if (context.Discounts.Any(x => x.DiscountId == id && !x.Deleted)) { var dbDiscount = context.Discounts.FirstOrDefault(x => x.DiscountId == id && !x.Deleted); dbDiscount.AppliesOnce = discount.AppliesOnce; dbDiscount.AppliesToProductType = discount.AppliesToProductType; dbDiscount.Code = discount.Code; dbDiscount.DiscountType = discount.DiscountType; dbDiscount.Duration = discount.Duration; dbDiscount.DurationUsageLimit = discount.DurationUsageLimit; dbDiscount.EndsAt = discount.EndsAt; dbDiscount.OncePerCustomer = discount.OncePerCustomer; dbDiscount.RestrictByEmail = discount.RestrictByEmail; dbDiscount.StartsAt = discount.StartsAt; dbDiscount.Status = discount.Status; dbDiscount.TimesUsed = discount.TimesUsed; dbDiscount.UsageLimit = discount.UsageLimit; dbDiscount.Value = discount.Value; context.Update(dbDiscount); if (context.SaveChanges() == 0) { return StatusCode(500, "Unable to update record."); } return NoContent(); }我觉得应该有更好的方法将新信息放入数据库中,但是我很难看到它。
1 回答
富国沪深
TA贡献1790条经验 获得超9个赞
Update方法用于所谓的强制更新,即,当您确定存在的实体断开连接时。它可以在不从数据库加载实体的情况下工作,并且只需更新所有属性即可。
以您的示例为例,强制更新如下所示:
if (context.Discounts.Any(x => x.DiscountId == id && !x.Deleted))
{
context.Update(discount);
context.SaveChanges();
}
如果只想更新已更改的属性(如果有),则应该加载数据库实体并使用该CurrentValues.UpdateValues方法来应用更改:
var dbDiscount = context.Discounts.FirstOrDefault(x => x.DiscountId == id && !x.Deleted);
if (dbDiscount != null)
{
context.Entry(dbDiscount).CurrentValues.SetValues(discount);
context.SaveChanges();
}
请注意,在这种情况下,EF可能根本不会发出更新命令(如果所有属性值都与原始属性值相同),即SaveChanges可以返回0,因此您不应将其用作成功的指示。实际上,您永远不应将其用于此目的,因为EF会抛出异常,这是有问题的。
- 1 回答
- 0 关注
- 139 浏览
添加回答
举报
0/150
提交
取消