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
//create the object
Task task = new Task{
task_name = src.taskName,
task_description = src.taskDescription
}
context.Tasks.InsertOnSubmit(task);
context.SubmitChanges();
//do second insert
Int32 taskIDFromLastInsert = task.task_id;
Resource res = new Resource{
resource_name = scr.ResourceName,
task_id = taskIDFromLastInsert // optional if you want to change your structure
}
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.
You should use
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.