如何更新实体框架子列表? [英] How to update child list in entity framework?
本文介绍了如何更新实体框架子列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这些机型:
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; }
}
在我的详情页面用户可以添加更多的电子邮件,删除exsting ...等...或更改现有之一。
如何更新收藏?
我会尝试这样的:
On my details page user is able to add more emails, delete exsting...etc...or change existing one. How to update collection? I tries this:
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;
字符串性能是很好的更新,我试图更新集合以同样的方式,但我得到重复的值。如何更新电子邮件?
String properties are updated nicely, I tried updating collection the same way, but I get duplicate values. How to update emails?
推荐答案
首先删除电子邮件去掉:
First delete removed 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;
}
}
这是更新编辑电子邮件后:
After that update edited emails:
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()
与标识新邮件 0
将被插入,你可以重复这个周期电话
。
And finally by calling db.SaveChanges()
new emails with Id of 0
Will be inserted and you can repeat this cycle for Phones
.
这篇关于如何更新实体框架子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文