我正在尝试Customer
使用 ASP.NET Web API 和 Entity Framework 5 代码优先更新我的数据库中的 a ,但它不起作用。我的实体如下所示:
public class CustomerModel
{
public int Id { get; set; }
public string Name { get; set; }
// More fields
public ICollection<CustomerTypeModel> CustomerTypes { get; set; }
}
public class CustomerTypeModel
{
public int Id { get; set; }
public string Type { get; set; }
[JsonIgnore]
public ICollection<CustomerModel> Customers { get; set; }
}
没什么特别的。我已经构建了一个 Web 界面,用户可以在其中通过提供名称并检查一个或多个客户类型来添加客户。当点击提交按钮时,数据被发送到我的 Web API 方法:
public void Put([FromBody]CustomerModel customer)
{
using (var context = new MyContext())
{
context.Customers.Attach(customer);
context.Entry(customer).State = EntityState.Modified;
context.SaveChanges();
}
}
这会更新客户字段,但会忽略相关的客户类型。传入的customer
对象确实包含一个CustomerTypes
它应该关联的列表:
[0] => { Id: 1, Type: "Finance", Customers: Null },
[1] => { Id: 2, Type: "Insurance", Customers: Null }
[2] => { Id: 3, Type: "Electronics", Customers: Null }
但是,EF 不会查看此列表并添加/删除关联实体,而是忽略它。新的关联会被忽略,现有的关联即使应该被删除也会保留。
我在将客户插入数据库时遇到了类似的问题,当我将这些实体的状态调整为EntityState.Unchanged
. 自然地,我尝试在我的更新场景中应用同样的魔法修复:
public void Put([FromBody]CustomerModel customer)
{
using (var context = new MyContext())
{
foreach (var customertype in customer.CustomerTypes)
{
context.Entry(customertype).State = EntityState.Unchanged;
}
context.Customers.Attach(customer);
context.Entry(customer).State = EntityState.Modified;
context.SaveChanges();
}
}
但 EF 一直显示相同的行为。
有想法该怎么解决这个吗?还是我真的应该手动清除列表CustomerTypes
然后手动添加它们?
提前致谢。
J.P