Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework – Inserting into multiple tables using foreign key

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

like image 437
Cragly Avatar asked Dec 14 '10 18:12

Cragly


1 Answers

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.
like image 187
jdmichal Avatar answered Nov 01 '22 19:11

jdmichal