1

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 个电子邮件地址的人正在正确保存,但在更新插入的人的电子邮件地址时不起作用。

4

2 回答 2

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; } 
}
于 2012-12-20T21:22:57.850 回答
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 列名称。其余的应该按原样工作。

于 2013-03-30T08:53:09.880 回答