简体   繁体   中英

c# batchcopy foreign key

I'm reading .txt files and inserting its data into datarows, these datarows are combined in a dataview and need to get pushed to a SQL database to a specific table, but it's lacking a foreign key and I don't know how to get it of another table.

The fields of the DataTable.Row should be stored in the [Fouten] table. These results need to be linked to the first table [Treinen] by the TreinId that's inserted as foreign key in the [Fouten] table.

But how can I retrieve this Id that I need to insert into the [Fouten] table that's available in the [Treinen] table?

Or should I use a different method to push a bunch of rows at the same time to the SQL database?

Maybe I can execute a stored procedure from here? that woudlve solve it too?

dt.Rows.Add(new object[] { datum, foutcode, omschrijving, module[module.Length - 1], tijd, teller, absentOfPresent});


using (SqlBulkCopy sbc = new SqlBulkCopy(GetConnectionString(), SqlBulkCopyOptions.KeepIdentity))
{
    sbc.DestinationTableName = "dbo.Fouten";
    sbc.BatchSize = 8000;

    sbc.ColumnMappings.Add("Datum", "Datum");
    sbc.ColumnMappings.Add("Foutcode", "FoutCode");
    sbc.ColumnMappings.Add("Omschrijving", "Omschrijving");
    sbc.ColumnMappings.Add("Module", "Module");
    sbc.ColumnMappings.Add("Time", "Time");
    sbc.ColumnMappings.Add("Teller", "Teller");
    sbc.ColumnMappings.Add("Mnemo", "Mnemo");
    //Retrieve TreinId from other table
    //Select TreinId Where Name = '1302';
    sbc.ColumnMappings.Add("??????", "TreinId");

    sbc.WriteToServer(dtInsertRows);
  }

在此输入图像描述

I don't think you can do the lookup at the same time as the bulk copy. Two other options:

1) Bulk copy the file data into a TEMPORARY table and then execute a SELECT..INTO query that joins the temporary table and the "TREINEN" table and inserts the data (with the foreign key) into the "FOUTEN" table

2) Perform a LINQ query in C# with the data table you already have joined with a second data table containing the data from "TREINEN", giving you a new data table that has the foreign key, and then copy that into the Fouten table

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM