Updating EntityFramework Nested Objects

What is wrong with the relation below that the nested object is never updated?

[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);
}

I just pass the device object and branch ID. All I'm trying to do is update the device branch ... However, the value never changes.

What am I missing?

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; }
+4
source share
2 answers

You received the value devicefrom the messages, and it is not tracked by context. Therefore, when you call db.SaveChanges, the context does not see any changes.

, 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();
+3

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);
}
+2

Source: https://habr.com/ru/post/1618520/


All Articles