我有一个API,我可以POST对象并更新数据库中的匹配记录。端点看起来像这样:
// POST: api/Spell
public IHttpActionResult Post([FromBody]Spell spell)
{
using (SpellContext db = new SpellContext())
{
var recordToUpdate = db.Spells.Where(x => x.id == spell.id).FirstOrDefault();
if (recordToUpdate != null)
{
recordToUpdate = spell;
db.SaveChanges();
return Ok("Spell " + spell.id + " (" + spell.name + ") Updated Successfully!");
}
else
{
return InternalServerError();
}
}
}
所以基本上只要有一个与传入法术相同ID的法术存在,我们就保存更改。
当我调用它时,我返回Ok,但数据库中没有更新。
如何来吗?
您从数据库中获得的拼写实例与DbContext分离。
public IHttpActionResult Post([FromBody]Spell spell)
你需要显式地将实体状态设置为Modified
if (recordToUpdate != null)
{
// Not needed: recordToUpdate = spell;
db.Entry(spell).State = EntityState.Modified;
db.SaveChanges();
return Ok("Spell " + spell.id + " (" + spell.name + ") Updated Successfully!");
}
注意,您不需要显式地将spell赋值给recordtouupdate,只要它们具有相同的实体键。
我的问题是我需要单独设置每个参数,而不是仅仅设置一个对象等于另一个对象。
更新API调用:
public IHttpActionResult Post([FromBody]Spell spell)
{
using (SpellContext db = new SpellContext())
{
var recordToUpdate = db.Spells.Where(x => x.id == spell.id).FirstOrDefault();
if (recordToUpdate != null)
{
recordToUpdate.name = spell.name;
recordToUpdate.desc = spell.desc;
recordToUpdate.higher_level = spell.higher_level;
recordToUpdate.page = spell.page;
recordToUpdate.range = spell.range;
recordToUpdate.components = spell.components;
recordToUpdate.material = spell.material;
recordToUpdate.ritual = spell.ritual;
recordToUpdate.duration = spell.duration;
recordToUpdate.concentration = spell.concentration;
recordToUpdate.casting_time = spell.casting_time;
recordToUpdate.level = spell.level;
recordToUpdate.school = spell.school;
recordToUpdate.class_name = spell.class_name;
db.SaveChanges();
return Ok("Spell " + spell.id + " (" + spell.name + ") Updated Successfully!");
}
else
{
return InternalServerError();
}
}
}