gpt4 book ai didi

asp.net-mvc - 使用 Web API 时为 JSON 尝试更新模型

转载 作者:行者123 更新时间:2023-12-02 03:23:35 25 4
gpt4 key购买 nike

我们在 System.Web.ModelBinding 下有 TryUpdateModel 以通过源中的可用数据部分更新模型。

如何在 Web API 中使用此模式?假设我的 JSON 结果只包含总共 10 个字段中的 9 个,我是否必须一个一个地设置字段值?

最佳答案

我假设:类型化模型和 Entity Framework 。我自己正在解决这个问题,但据我了解,如果您将值发布到您的 API,那么它们将被初始化为默认值(例如,字符串为 null),或者如果您包含验证属性,则 API 可能会使模型失败验证步骤。

我遇到了一个问题,即创建和更新的时间戳在新命令和更新命令中被覆盖。这 ?运算符(operator)帮助创建,但更新已关闭,然后我找到了我需要的 DatabaseGenerated 属性。

    [Column("db_created")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? Created { get; set; }

如果您不想用默认值覆盖某些字段,那么您需要对当前实例进行手动映射。因此,获取它并更新您更改的值。注意:您需要更新从数据库中获取的新对象,因为 EF 现在在您保存更改时跟踪该实例。

例如:

    // PUT: api/Customer/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutCustomer(int id, Customer updatedCustomer)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);

if (id != updatedCustomer.ID)
return BadRequest();

var currentCustomer = await db.Customers.FindAsync(id);
updatedCustomer.Created = currentCustomer.Created;
currentCustomer.Name = updatedCustomer.Name;
currentCustomer.Description = updatedCustomer.Description;
//This is nullable in the model e.g. public DateTime? Updated;
currentCustomer.Updated = null;
db.Entry(currentCustomer).State = EntityState.Modified;

try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CustomerExists(id))
return NotFound();
else
throw;
}
return StatusCode(HttpStatusCode.NoContent);
}

关于asp.net-mvc - 使用 Web API 时为 JSON 尝试更新模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31582890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com