Here is the scenario (ADO.NET Entity Framework and C#).
Contact*:
String name;
Address addr;
Address*:
String street;
String city;
*this is not the real code, but you get the picture
I am trying to create a Windows Form that appears flat to the user. In other words, the Form will have four fields (name,addr,street,city), and when the users clicks on the Add button in a bindingSourceNavigator, I want to create a new instance of Contact
such that Contact.addr
is a reference to a newly created Address
.
If I were only working with objects this would be simple, but I'm trying to create a new row in the table that backs Address
.
Here is what I've tried so far:
private void contactBindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
Contact newContact = new Contact();
Address newContactAddr = new Address();
newContact.Address = newContactAddr;
newContactAddr.Contacts.Add(newContact);
//I realize I don't need the Contact list reference in Address,
//but VS2010 created it, so I'm just adding the new Contact to
//the list for now.
e.NewObject = newContact;
}
private void contactBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
contactBindingSource.EndEdit();
context.SaveChanges(); //throws UpdateException
}
Some background: The Form has a binding source for Contact
, and this method is the event handler for when new Contact
s are created. I read on MSDN that this is how one modifies the object before it is actually added to the BindingSource. context
refers to my entity model.
What happens: When I click the add button, I am able to enter in the contact information. But when I click the save button, I get an UpdateException
. I suspect this is because I did not create the Address
properly, but being new to the ADO.NET framework (and .NET programming in general), I don't really know the correct way to do this.