将数据表合并到数据集中,并将更改保存回数据源

时间:2016-07-27 21:02:44

标签: c#

首先是c#项目,我需要将远程SQL Server的记录拉入localDB实例。读了这么多关于脑死亡的文档。 Source是一个npsql数据源。 Target是localdb实例我用相同的模式构建了本地表。我不认为SqlBulkCopy是正确的解决方案,所以我试图改变并添加。虽然我在代码中没有错误,但是localdb实例没有更新。

DataTable custMsrDT = this.MeasureDB.getMsrCustomerDT();

using (SqlConnection connection = new SqlConnection(LocalDB.connStringLocalDB))
{
    connection.Open();

    SqlDataAdapter da = new SqlDataAdapter("SELECT id, crm_customer_id, jb_customer_id, fname, lname, phone, alt_phone, email, street_address, unit_number, neighborhood, city, state, zip, county FROM dbo.customer;", connection);

    DataSet localDS = new DataSet();

    da.Fill(localDS, "customer");
    SqlCommandBuilder builder = new SqlCommandBuilder(da);

    localDS.Tables["customer"].RowChanged += new System.Data.DataRowChangeEventHandler(Row_Changed);

    localDS.Tables["customer"].Merge(custMsrDT, true, MissingSchemaAction.Add);

    da.Update(localDS, "customer");
}

1 个答案:

答案 0 :(得分:0)

想通了。使用table.merge函数不是答案。它归结为理解如何设置行状态。在原来,rowstate总是"没有变化"因此datatable.update没有做任何事情。使用load function on the table是正确的方法。

    DataTable custMsrDT = this.MeasureDB.getMsrCustomerDT();

    using (SqlConnection connection = new SqlConnection(LocalDB.connStringLocalDB))
    {
        connection.Open();

        SqlDataAdapter da = new SqlDataAdapter("SELECT id, crm_customer_id, jb_customer_id, fname, lname, phone, alt_phone, email, street_address, unit_number, neighborhood, city, state, zip, county FROM dbo.customer;", connection);

        DataSet localDS = new DataSet();

        da.Fill(localDS, "customer");

        SqlCommandBuilder builder = new SqlCommandBuilder(da);

        localDS.Tables["customer"].RowChanged += new System.Data.DataRowChangeEventHandler(Row_Changed);


        //localDS.Tables["customer"].Merge(custMsrDT, true, MissingSchemaAction.Add);


        using (DataTableReader changeReader = new DataTableReader(custMsrDT))
        {

            localDS.Tables["customer"].Load(changeReader, LoadOption.Upsert);

        }

        PrintColumns(localDS.Tables["customer"]);

        DisplayRowState(localDS.Tables["customer"]);

        da.Update(localDS, "customer")