Entity Framework - insert into multiple tables using a foreign key

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

I had a problem adding a new record to a UserRecord object and then adding a UserDetail object that uses the newly created UserRecordId as its primary key. The code shown below was used when my database was one-to-many, but when I change it to a one-to-one relationship, I get the error highlighted in the image below. alt text

I believe that it does not work, because now there is no UserDetails property associated with UserRecord, because its now a one-to-one relationship. My question is: how do I now insert new UserRecord and corresponding UserDetail objects with a one-to-one relationship?

Any help on this subject is much appreciated, as well as when searching the Internet and trying to find many different things without success.

Greetings

Cragly

+6
entity-framework entity-framework-4
source share
1 answer

Your UserDetail object must have a property that references the UserRecord object. (Maybe it's called User ? If I read the navigation section correctly below). If you set this property to your new, uncommitted UserRecord object, it will automatically populate the key when it completes 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. 
+15
source share

All Articles