实体框架 - 使用外键插入多个表 [英] Entity Framework – Inserting into multiple tables using foreign key

查看:147
本文介绍了实体框架 - 使用外键插入多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是EF的相对新人,并使用EF4创建了一个简单的模型(见下文)。



我有将新记录插入到UserRecord实体中并随后添加使用新创建的UserRecordId作为其主键的UserDetail实体的问题。当我的数据库有一对多的关系时,下面显示的代码用于工作,但是当我将其更改为一对一的关系时,我得到下面图中突出显示的错误。



我相信不起作用,因为现在没有与UserRecord关联的UserDetails属性,因为它现在是一对一的关系。我的问题是如何现在插入新的UserRecord和相应的UserDetail实体与一对一的关系?



对此的任何帮助是非常感谢,因为已经在搜索网络,尝试各种不同的事情,没有成功。



干杯



Cragly

解决方案

您的 UserDetail 对象应该有一个属性链接回 UserRecord 对象。 (这可能称为用户?如果正在正确阅读导航部分)如果将该属性设置为新的未提交的 UserRecord 对象,当它提交两个对象时,它将自动填写该键。

  UserRecord userRecord = new UserRecord (); 
// any

UserDetail userDetail = new UserDetail();
userDetail.User = userRecord; //这将在提交时自动填充FK。
//任何

//将userRecord和userDetail添加到上下文并提交。


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

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.

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

解决方案

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.

这篇关于实体框架 - 使用外键插入多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆