1
votes

I have Customer and Address classes, something like this:

public class Customer
{
    [PrimaryKey]
    public int Id { get; set; }
    public string CustomerName { get; set; }
    public int ShippingAddressId { get; set; }
    [ForeignKey("ShippingAddressId")]
    public Address ShippingAddress { get; set; }
}
public class Address
{
    [PrimaryKey]
    public int Id { get; set; }
    public string City { get; set; }
}

When I call a Web API to update the Customer, I pass an edited Customer object to this method. For example, I edit 2 properties: Customer.CustomerName and Customer.ShippingAddress.City

AuthenticationResult ar = await new AuthHelper().AcquireTokenSilentAsync();
if (ar.Token == null) return false;
using (var json = new StringContent(JsonConvert.SerializeObject(entity), UnicodeEncoding.UTF8, "application/json"))
using (HttpClient client = new HttpClient())
{
    client.BaseAddress = new Uri(Settings.ApiUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ar.Token);
    using (HttpResponseMessage response = await client.PutAsync("api/" + type.ToString() + "/" + id, json))
    {
        response.EnsureSuccessStatusCode();
        return await InsertOrReplaceResponse(type, response);
    }
}

Here is the Web API:

[HttpPut("{id}")]
public async Task<IActionResult> PutCustomer([FromRoute] int id, [FromBody] Customer customer)
{
    _context.Entry(customer).State = EntityState.Modified;

    await _context.SaveChangesAsync();

    return new StatusCodeResult(StatusCodes.Status204NoContent);
}

However, only Customer.CustomerName gets updated. The foreign key data (Customer.ShippingAddress.City) isn't updated in the Address table.

Any idea what I'm doing wrong?

Thanks!

1

1 Answers

0
votes

Generally, I would expect the child Address entity to be update as well because you use foreign key association which also should be the default for one-to-one mappings (see here for more details). However, it seems that something is not setup right and you get independent association behavior where you have to manage child entity state yourself. Should be a simple fix in your case:

_context.Entry(customer).State = EntityState.Modified;
_context.Entry(customer.ShippingAddress).State = EntityState.Modified;