Firstly I notice you commented out the SaveChanges
call in your action. If you don't save the changes then nothing will be created. The default behavior if the controller returns/fails before you save changes is to throw away all your changes.
EF is based upon proxies and relationships. You're thinking about this in terms of PK/FK relationships. Assuming you have set up the relationship in EF such that a Contact has an associated Customer and/or Customer has one or more Contact objects then ensure your navigation properties are marked as virtual. To create a new customer and contact you would simply create the customer object and add to your Customers set. Ensure the Customer object has a Contact assigned in its navigation property. When EF is told to add the customer it will see that there is also a Contact and, since the Contact is not being tracked yet, will automatically add the contact to the DB as well. You don't need to explicitly add it. Behind the scenes EF will (as part of the transaction) insert the Customer row and then insert the Contact row using the ID that was given when it inserted the Customer row. You don't have to do this manually.
More interesting is that once you call SaveChanges
then EF, because of the proxy object for the virtual navigation property, will update the Id properties on your objects for you. So if you were to check the value of Customer.ID
after the save call you'd see it is no longer invalid. The Contact.Id
will be the same way. But unfortunately you'll still see a mixture of other behavior. For example the Customer
property on Contact
, if any, will probably not be set. EF caches data when it loads things and won't refresh them. So you should take a look at your objects after saving to see what EF actually set. I wouldn't be surprised if Contact.CustomerId
is also not set as it isn't a virtual property. In general virtual nav properties will be updated by EF after save but other properties will not be.