<分区> 分区>
我正在使用 Entity Framework Core 连接到 postgres 数据库,在 ASP.NET Core 2.0 上开发一个 web api 项目。
下面的 PUT 方法没有问题,但我觉得我可能误解了更新方法的使用,我也觉得应该有一个更优雅的解决方案来更新现有对象,以保持 PUT 请求的方式(不是补丁)。
// 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();
}
else
{
return NotFound();
}
}
}
else
{
return BadRequest(ModelState);
}
}
我觉得应该有更好的方法将新信息放入数据库,但我看不到它。
编辑: 正如 Ivan 正确建议的那样,我对优雅/更好的想法是更少的代码实现相同的效果和更好地使用工具。 感谢所有建议 Automapper 删除变量从 dto 到模型的繁琐重新映射的人。还要特别感谢 Ivan Stoev,他解释了强制更新和部分更新的工作原理,以及最好使用异常而不是受影响的行数进行错误处理的想法。
