开发者

Update related entities Entity Framework DbContext

开发者 https://www.devze.com 2023-04-01 01:58 出处:网络
I\'m using EF with a DbContext and several POCO entities public class Customer { public int ID { get; set; }

I'm using EF with a DbContext and several POCO entities

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

Now, I need to update a quotation

        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.ContactPerson开发者_开发技巧Assigned = myDB.ContactPersons.Find(((ContactPerson)this.comboBox_YourReference.SelectedItem).ID);
            quotationDB.DateCreated = this.dateTimePicker_dateQuoted.Value;

 myDB.SaveChanges();
                }

All the fields in quotationDB will update, except for quotationDB.ContactPersonAssigned which will never be updated. Why? The actual object updates correctly, but no changes are save into the database.


you need to define navigation properties as virtual

 public virtual ContactPerson ContactPersonAssigned { get; set; }
0

精彩评论

暂无评论...
验证码 换一张
取 消