public class PhoneNumber {
public string Number {get; set;}
public string Type {get; set;}
}
public class Customer {
public ICollection<PhoneNumber> phones {get; set;}
}
我正在将一个Customer对象发布(放置)到我的webapi中。发布对象中包含的任何电话号码都是我要保存在数据库中的 only 电话号码。如果数据库中以前有该客户的号码,我希望将其删除。
_context.Update(model);
我已经尝试了上述方法,但是它只会添加或编辑现有的电话号码。数据库中存在但发布对象中不存在的数字不会被删除。
答案 0 :(得分:0)
您可以尝试修改实体以为PhoneNumber定义组合键,该组合键由PhoneNumber的ID和客户的外键组成:
public class Customer
{
[Key]
public int CustomerId { get; set; }
public ICollection<PhoneNumber> phones { get; set; }
}
public class PhoneNumber
{
[Key, ForeignKey("Customer"), Column(Order = 1)]
public int CustomerId { get; set; }
[Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PhoneNumberId { get; set; }
public string Number { get; set; }
public string Type { get; set; }
public Customer customer { get; set; }
}
要配置组合键,请在DbConext的重写方法OnModelCreating中使用Fluent API配置:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PhoneNumber>()
.HasKey(c => new { c.CustomerId, c.PhoneNumberId });
}
更新数据库:Add-migration,Update-Database。
然后在api中获取实体后,您可以更新Customer和child集合,如:
Customer cs = new Customer();
cs.CustomerId = 1;
cs.name = "gg";
cs.phones = new List<PhoneNumber>();
cs.phones.Add(new PhoneNumber() { CustomerId = 1, Number = "12", Type = "gg" });
cs.phones.Add(new PhoneNumber() { CustomerId = 1, Number = "44", Type = "TT" });
var customer = db.customers.Include("phones").Single(o => o.CustomerId == cs.CustomerId);
customer.phones = cs.phones;
db.SaveChanges();