Entity Framework – Inserting into multiple tables

2020-02-23 04:22发布

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

1条回答
家丑人穷心不美
2楼-- · 2020-02-23 04:35

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.
查看更多
登录 后发表回答