这些是模型:
public class Contact
{
public Contact()
{
Emails = new List<Email>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Address { get; set; }
public ICollection<Email> Emails { get; set; }
}
public class Email
{
public int Id { get; set; }
public string Name { get; set; }
public virtual int ContactId { get; set; }
}
在我的详细信息页面上,用户可以添加更多电子邮件、删除现有...等...或更改现有电子邮件。 如何更新收藏? 我试试这个:
var contactFromDb = db.Contacts.Include("Emails").Include("Telephones").Where(x => x.Id == contact.Id).FirstOrDefault();
contactFromDb.Address = contact.Address;
contactFromDb.Name = contact.Name;
contactFromDb.Surname = contact.Surname;
contactFromDb.Telephones = contact.Telephones;
contactFromDb.Emails = contact.Emails;
字符串属性更新得很好,我尝试以同样的方式更新集合,但我得到了重复的值。如何更新邮件?
最佳答案
首先删除删除的邮件:
var contactFromDb = db.Contacts.Include("Emails").Include("Telephones").FirstOrDefault(x => x.Id == updatedContact.Id);
contactFromDb.Address = updatedContact.Address;
contactFromDb.Name = updatedContact.Name;
contactFromDb.Surname = updatedContact.Surname;
// Delete removed emails
var emailsToDelete = (from email in contactFromDb.Emails
let item = updatedContact.Emails.SingleOrDefault(i => i.Id == email.Id)
where item == null
select email).ToList();
if (emailsToDelete.Any())
{
foreach (var email in emailsToDelete)
{
db.Entry(email).State = EntityState.Deleted;
}
}
更新编辑后的电子邮件:
foreach (var email in updatedContact.Emails)
{
// If id of an email is not equal to 0, it's not new email and it should be updated
if (email.Id > 0)
{
var emailInDb = contactFromDb.Emails.Single(e => e.Id == email.Id);
db.Entry(emailInDb).CurrentValues.SetValues(email);
db.Entry(emailInDb).State = EntityState.Modified;
}
}
最后,通过调用 db.SaveChanges()
,Id 为 0
的新电子邮件将被插入,您可以为 Phone
重复此循环.
关于c# - 如何更新 Entity Framework 中的子列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25831959/