I have 3 tables. I create a task and upload a resource at the same time. The data is saved in two tables – one for task information and one for the resource.
I am trying to insert the primary keys of the two tables into a third table. The first table is called Task and has task_id as a primary key, task_name and task_description. The second one is – Resource and has resource_id as a primary key and resource_name. Both id’s have the auto increment option, so when I enter data to the table, I don’t fill the ids.
I want to insert task_id and resource_id into a third table called Task_resource. It has a primary key task_resource_id(again with auto increment option).
The question is how to do it, since I don’t know the id’s?
The reason for this is that one task can have many resources and in the third table I can combine them, and therefore search of them(for example something like SELECT data from the other 2 tables WHERE task_id=1).
I am having a asp.net Web Application and a mssql database. I use c#.
I know that a possible solution could be inserting a column called task_id into the Resource table which references the task_id in Task.
But then again, how to insert that id, since I don’t know it ?
Do the insert on the first table and then return the scope_identity() from the query. Then when you insert into the second table you have the ID? Or if you are using LINQ
context.Resources.InsertOnSubmit(res);
context.SubmitChanges();
Int32 resourceIDFromLastInsert = resource_id;
You now have both ID’s if you really want to insert into third table
It is a clean way to reference your data
After the inserts run your query against the data.