更新相关实体Entity Framework DbContext

时间:2011-09-01 14:01:35

标签: entity-framework dbcontext

我正在使用EF与DbContext和几个POCO实体

     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 个答案:

答案 0 :(得分:1)

您需要将导航属性定义为虚拟

 public virtual ContactPerson ContactPersonAssigned { get; set; }