EF代码首次更新不适用于一对多关系

时间:2012-12-20 06:36:54

标签: ef-code-first

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个电子邮件地址的人正在妥善保存,但更新插入人员的电子邮件地址时无效。

2 个答案:

答案 0 :(得分:0)

你应该这样做:

 public class Person 
{    
    public int Id { get; set; } 
    public string Name{ get; set; } 
    public List<Email> Emails { get; set; } 
}

public class Email 
{ 
    public int Id { get; set; } //This will generate PKey.
    public virtual Person person { get; set; } //This will create the FKey.
    public string EmailAddress { get; set; } 
}

答案 1 :(得分:0)

您遇到的问题是您需要将ForeignKeyAttribute应用于您明确包含的任何FK:

    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; } 

        [ForeignKey("Person")]
        public int PersonId { get; set; } 
    public virtual Person Person { get; set; }

        public string EmailAddress { get; set; } 
    }

通过应用该属性,您可以告诉EF Migrations使用“PersonId”作为“Person”关系的FK列名。其余的应该按原样运作。