DataTable.Cloneの攻撃
DataTableにユニークキーを設定する - 匣の向こう側 - あまりに.NETな
ユニークキー問題は解決したと思っていたのですが、思わぬ落とし穴が。
using System; using System.Data; class Program { static void Main (string args) { DataTable t = new DataTable (); t.Columns.Add ("FirstName"); t.Columns.Add ("LastName"); t.Columns.Add ("Age",typeof (int)); t.PrimaryKey = new { t.Columns[0],t.Columns[1] }; foreach (var key in t.PrimaryKey) key.AllowDBNull = true; Console.WriteLine ("-- Original --"); Dump (t); Console.WriteLine ("-- Clone --"); Dump (t.Clone ()); } static void Dump (DataTable t) { foreach (var key in t.PrimaryKey) Console.WriteLine ("{0}.AllowDBNull={1}",key.ColumnName,key.AllowDBNull); } } /* 結果 -- Original -- FirstName.AllowDBNull=True LastName.AllowDBNull=True -- Clone -- FirstName.AllowDBNull=False LastName.AllowDBNull=False */
個人的には、AllowDBNullの値がコピーされないのはバグだと思いますよ。しょうがないのでヘルパーメソッドを用意してDataTable.Cloneを呼び出している個所を全部書き直しました。