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.
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:
Create object B
Add object B to context
Create object A
Set the navigation property in A which points to B (AB) to value B.
Add object A to context
Save changes in context
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.