EF 代码第一次更新不适用于一对多关系
我有 2 个实体
// Save
public class Person
{
public int Id { get; set; }
public string Name{ get; set; }
public virtual List<Email> Emails { get; set; }
}
public class Email
{
public int Id { get; set; }
public int PersonId { get; set; }
public virtual Person person { get; set; }
public string EmailAddress { get; set; }
}
EFContext context = new EFContext();
Person person;
Email email;
person = new Person();
person.Name = "Rocky";
person.Emails = new List<Email>();
email = new Email { EmailAddress = "rocky@frostbitefalls.com" };
person.Emails.Add(email);
email = new Email { EmailAddress = "rocky@squirrel.com" };
person.Emails.Add(email);
context.People.Add(person);
context.SaveChanges();
// Update
person = new Person();
person.Id=1;
person.Name = "Rocky Altered";
person.Emails = new List<Email>();
email = new Email {Id=1, EmailAddress = "Altered_rocky@frostbitefalls.com" };
person.Emails.Add(email);
email = new Email {Id=2, EmailAddress = "Altered_rocky@squirrel.com" };
person.Emails.Add(email);
UpdatePerson(person);
public bool UpdatePerson(Person entity)
{
var updatePerson = GetPersonById(entity.Id);
updatePerson.Name=entity.Name;
updatePerson.Emails=entity.Emails;
DataContext.Entry<Person>(updatePerson).State = EntityState.Modified;
DataContext.SaveChanges();
DataContext.Entry<Person>(updatePerson).Reload();
}
具有 2 个电子邮件地址的人正在正确保存,但在更新插入的人的电子邮件地址时不起作用。