views:

34

answers:

1

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 Contacts 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.

A: 

An example: I have 3 tables, Users, UserRoles and Roles.

when i create a user i want this user to receive a role and i would then do

using(DatabaseEntities db = new DatabaseEntities())
{
    //creates the user and add the properties except roles
    Users user = new Users();
    user.username = "Test";

    //get an existing role
    var role = db.Roles.SingleOrDefault(r => r.roleName == "User");

    //adds the userid and roleid in to userRoles
    user.Roles.Add(role);

    db.Users.AddObject(user);

    //saves it to the db
    db.SaveChanges();
}

so, in order for it to work in your example, you would first need to insert One of them to the db before using it in order to save the other object along with the row to the table that links them together.

I hope this simple example helps you.

Joakim