EF插入多个相关表 [英] EF insert multiple related tables

查看:281
本文介绍了EF插入多个相关表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想数据保存到从使用LINQ /实体框架C#应用程序的数据库。插入到一个表是很简单的,但我不知道如何将数据插入它们都通过自动递增的身份互连三个表?
这是一刮,所以我以一个线程,这一切的帖子 - 每个 ThreadTitle 每个发表用户相关联(而不是实际的表名)。

I'm trying to save data into a database from a C# app using Linq/Entity Framework. Inserting to a single table is simple enough, but I'm not sure how to insert data into three tables which are all interconnected with auto-increment identities? This is for a scrape, so I'm taking a thread and all it's posts - each ThreadTitle and each Post is associated with a User (not actual table names).

我的设计理念是为了凑全螺纹到内存中,然后做一个批量插入。为了减少负荷,我希望有一些方法来保持关系的约束,而不做一下起坐,多个插入等。

My design idea was to scrape a full thread into memory and then do a "batch" insert. To reduce load, I was hoping there is some way to maintain the relationship constraints, without doing look-ups, multiple inserts etc.

推荐答案

如果您要保存两个记录这是相关的,因为有个FK一(A)到另一个(b),做到以下几点:

If you want to save two records which are related because there is a FK in one (A) to the other one (B), do the following:


  • 创建对象b

  • Create object B

对象b添加到关联

创建对象A

设置导航属性在指向b(AB),以b值。

Set the navigation property in A which points to B (A.B) to value B.

对象的添加上下文

保存环境的变化

您实际上并不具备这两个对象添加到背景下,一个就够了,因为有相关EF可以找到'树'的一切。
EF会找出自身有什么插入第一,并设置正确的ID。

You don't actually have to add both objects to the context, one is enough, since there are related EF can find everything 'in the tree'. EF will figure out by itself what to insert first and set the correct id's.

这是你是什么意思?希望这可以帮助。

Is this what you mean? Hope this helps.

这篇关于EF插入多个相关表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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