2011-09-01 134 views
0

我使用EF用的DbContext和幾個POCO實體更新相關實體的實體框架的DbContext

 public class Customer 
    { 
     public int ID { get; set; } 

     public string CompanyName { get; set; } 

     public string Address { get; set; } 

     public string Email { get; set; } 

     public string Phone { get; set; } 

     public List<Project> Projects { get; set; } 

     public List<ContactPerson> ContactPersons { get; set; } 
} 

    public class ContactPerson 
     { 
      public int ID { get; set; } 

      public string Name { get; set; } 

      public string Email { get; set; } 

      public string Phone { get; set; } 
} 



public class Quotation 
    { 
     public int ID { get; set; } 

     public string QuotationName { get; set; } 

     public DateTime DateCreated { get; set; } 

     public ContactPerson ContactPersonAssigned { get; set; } 

     public string OurReference { get; set; } 

     public string QuotationDataString { get; set; } 
} 

現在,我需要更新報價

 using (var myDB = new MyDB()) 
     { 
      Quotation quotationDB = myDB.Quotations.Find(this.quotation.ID); 
      quotationDB.QuotationName = textBox_name.Text; 
      quotationDB.OurReference = textBox_quotedBy.Text; 
      quotationDB.ContactPersonAssigned = null; 
      quotationDB.ContactPersonAssigned = myDB.ContactPersons.Find(((ContactPerson)this.comboBox_YourReference.SelectedItem).ID); 
      quotationDB.DateCreated = this.dateTimePicker_dateQuoted.Value; 

myDB.SaveChanges(); 
       } 

所有quotationDB字段將更新,除了quotationDB.ContactPersonAssigned,它永遠不會被更新。爲什麼?實際的對象正確更新,但沒有更改保存到數據庫中。

回答

1

您需要定義導航屬性爲虛擬

public virtual ContactPerson ContactPersonAssigned { get; set; } 
+0

我想這沒有結果。無論如何,爲什麼它應該是虛擬的? – Francesco

+0

已修復。我做了另一個錯誤,並且 – Francesco

+0

太棒了。然後用另一個錯誤更新你的文章。這將是對他人的幫助。 –