ASP .NET Web API SaveChangesAsync与外键数据

时间:2016-07-31 15:18:03

标签: asp.net entity-framework asp.net-web-api asp.net-web-api2

我有Customer和Address类,如下所示:

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

当我调用Web API来更新Customer时,我将已编辑的Customer对象传递给此方法。例如,我编辑了2个属性:Customer.CustomerName和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);
    }
}

以下是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);
}

但是,只有Customer.CustomerName会更新。外部密钥数据(Customer.ShippingAddress.City)未在地址表中更新。

知道我做错了吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

通常,我希望子warning: Ignoring InnerClasses attribute for an anonymous inner class (com.jcraft.jsch.Channel$1) that doesn't come with an associated EnclosingMethod attribute. This class was probably produced by a compiler that did not target the modern .class file format. The recommended solution is to recompile the class from source, using an up-to-date compiler and without specifying any "-target" type options. 实体也可以更新,因为你使用外键关联,这也应该是一对一映射的默认值(有关更多详细信息,请参阅here )。但是,似乎某些东西设置不正确并且您获得了独立的关联行为,您必须自己管理子实体状态。在你的情况下应该是一个简单的解决方案:

Address