如何将集合转换为DataTable for Ado.Net SqlDataAdapter.Update?

时间:2014-06-30 17:34:59

标签: c# ado.net

如何完成以下函数,该函数接受已删除,插入和更新记录的三个集合参数,并将集合转换为DataTable DataAdapter以更新表格?

我找到了一种在How to fill a datatable with List<T>将List转换为DataTable的方法。但是,它没有在DataTable中设置插入,更新和删除标志?

void Save(
    IEnumerable<int> deleted, 
    IEnumerable<Poco1> inserted, 
    IEnumerable<Poco1> updated)
{
    var dt = new DataTable(); 
    .... // Initialize dt with deleted, inserted and update?

    using (var con = new SqlConnection(ConnectionStr))
    {
        con.Open();
        var da = new SqlDataAdapter("select * from table", con);
        da.Update(dt);
    }
}

或者有更好的方法从这三个集合更新数据库表吗? (C#3.5)

2 个答案:

答案 0 :(得分:1)

首先,您还想要定义插入,更新和删除命令:

// Create the other commands.
da.InsertCommand = new SqlCommand("...how to insert");

da.UpdateCommand = new SqlCommand("...how to update");

da.DeleteCommand = new SqlCommand("...how to delete");

或者,您可以尝试使用DbCommandBuilder在运行时为您执行此操作:

// Create the DbCommandBuilder.
DbCommandBuilder builder = factory.CreateCommandBuilder();
builder.DataAdapter = da;

// Get the insert, update and delete commands.
da.InsertCommand = builder.GetInsertCommand();
da.UpdateCommand = builder.GetUpdateCommand();
da.DeleteCommand = builder.GetDeleteCommand();

接下来,您需要定义DataTables以匹配您要定位的表格:

DataTable dt = new DataTable();
dt.Columns.Add(add your columns...)

然后您需要向DataTable添加行,确保将该行标记为已插入,更新或删除。

DataRow dr = dt.NewRow();
dr["your column"] = ...
// Don't forget to add the row to the table!
dt.Rows.Add(dr);
// Once the row is added then go ahead and mark it as deleted, modified or new
dr.Delete()
// or
dr.SetAdded();
// or
dr.SetModified();

答案 1 :(得分:0)

它不会按照你的方式工作,这样做

 using (var con = new SqlConnection(ConnectionStr))
    {
        con.Open();
        var da = new SqlDataAdapter("select * from table", con);
        var ds=new DataSet();
        da.Fill(ds);
        var dt= ds.Tables[0];
        // all deleted rows 
        foreach(DataRow dr in dt.Rows.ToList())
{
    if(deleted.ToList().Contains((int)dr["id"]))
{
        dr.Delete();
}
//all updated rows 
foreach(var poco in updated.ToList()
{
  DataRow dr = table.Select("id="+poco.id).FirstOrDefault();
  dr["field1]=poco.feild1 
  ....set all updated values 

}
//all inserted rows 
foreach(var poco in inserted.ToList())
{
  var dr= dt.NewRow();
  dr["id"]=poco.id;
  ..set all fields
  dt.Rows.Add(dr);
}
}
        dt.Accept
        da.Update(dt);
    }