EntityFramework嵌套对象更新

时间:2015-12-04 02:53:49

标签: c# entity-framework asp.net-web-api

嵌套对象永远不会更新,下面有什么错误?

[Route("api/branches/{id}/devices")]
public async Task<IHttpActionResult> PutDevice(int id, Device device)
{
    Branch branch = await  db.Branches.Include("devices").FirstAsync(b => b.id == id);
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    if (branch == null)
    {
        return NotFound();
    }

    device.branch = branch;

    try
    {
        await db.SaveChangesAsync();
    }

    catch (DbUpdateConcurrencyException)
    {
        if (!BranchExists(id))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }
    return StatusCode(HttpStatusCode.NoContent);
}

我只是传递一个设备对象和分支ID。我想要做的就是更新设备的分支......但是,值永远不会改变。

我错过了什么?

Device.cs

public class Device
{
    public Device()
    {
        date_created = DateTime.UtcNow;
    }

    [Key]
    public int id { get; set; }

    public string name { get; set; }

    public virtual Branch branch { get; set; }

    public int branch_id { get; set; }

2 个答案:

答案 0 :(得分:4)

您收到了来自帖子值的device,并且未按上下文进行跟踪。因此,当您致电db.SaveChanges时,上下文未看到任何更改。

正如您在评论中提到的那样,branch_id课程中有device,您可以将id设置为branch_id,而您不需要执行查询加载一个分支。

添加新设备:

device.branch_id = id;   
db.Devices.Add(device);
db.SaveChanges();

编辑现有设备:

device.branch_id = id;   
db.Entry(device).State = EntityState.Modified;
db.SaveChanges();

答案 1 :(得分:2)

&lt; p&gt;您的变量设备不在EF上下文中,因此EF不知道它,并且他永远不会更改设备。&lt; / p&gt; &lt; p&gt;你可以尝试这样的事情:&lt; / p&gt; &lt; pre class =“lang-cs prettyprint-override”&gt;&lt; code&gt; [Route(“api / branches / {id} / devices”)] public async Task&lt; IHttpActionResult&gt; PutDevice(int id,Device device) {     Branch branch = await db.Branches.Include(“devices”)。FirstAsync(b =&gt; b.id == id);     Device dbDevice = await db.Devices.Find(device.id);     if(!ModelState.IsValid)     {         返回BadRequest(ModelState);     }     if(branch == null || dbDevice == null)     {         return NotFound();     }     dbDevice.branch = branch;     尝试     {         等待db.SaveChangesAsync();     }     catch(DbUpdateConcurrencyException)     {         if(!BranchExists(id))         {             return NotFound();         }         其他         {             扔;         }     }     return StatusCode(HttpStatusCode.NoContent); } &LT; /代码&GT;&LT; /预&GT;