EntityFramework嵌套对象更新

本文关键字:更新 对象 嵌套 EntityFramework | 更新日期: 2023-09-27 18:25:45

下面的内容有什么错误,以至于嵌套对象永远不会更新?

[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。我所要做的就是更新设备的分支。。。但是,该值永远不会改变。

我错过了什么?

设备.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; }

EntityFramework嵌套对象更新

您收到了来自post值的device,它不受上下文跟踪。因此,当您调用db.SaveChanges时,上下文不会看到任何更改。

正如您在评论中提到的,device类中有branch_id,您可以将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();

您的变量设备不在EF上下文中,所以EF不知道它,他永远不会更改设备。

你可以试试这样的东西:

[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);
    Device dbDevice = await  db.Devices.Find(device.id);
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    if (branch == null || dbDevice == null)
    {
        return NotFound();
    }
    dbDevice.branch = branch;
    try
    {
        await db.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!BranchExists(id))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }
    return StatusCode(HttpStatusCode.NoContent);
}