Entity-framework – Entity Framework – Inserting into multiple tables using foreign key

entity-frameworkentity-framework-4

I am a relative newby to EF and have created a simple model (see below) using EF4.
alt text

I am having a problem inserting a new record into the UserRecord entity and subsequently adding the UserDetail entity which uses the newly created UserRecordId as its primary key. The code shown below used to work when my database had a one-to-many relationship but when I change this to a one-to-one relationship I get the error highlighted in the image below.
alt text

I believe its not working as there is now no UserDetails property associated with the UserRecord because it’s now a one-to-one relationship. My question is how do I now insert new UserRecord and corresponding UserDetail entities with a one-to-one relationship?

Any help on this one is much appreciated as have been on searching the web and trying a variety of different things without success.

Cheers

Cragly

Best Answer

Your UserDetail object should have a property that links back to the UserRecord object. (It is maybe called User? If I'm reading the navigation section below correctly.) If you set that property to your new, uncommitted UserRecord object, it will automatically fill in the key when it commits both objects.

UserRecord userRecord = new UserRecord();
// whatever

UserDetail userDetail = new UserDetail();
userDetail.User = userRecord; // This will auto-fill the FK during commit.
// whatever

// Add both userRecord and userDetail to the context and commit.