在DataRow中放置CreatedDate和ModifiedDate的好地方在哪里?

时间:2011-02-23 10:12:01

标签: c# .net datarow

我有以下代码

public class SpecialItemRow : DataRow
    {
        public SpecialItemRow(DataRowBuilder builder)
            : base(builder)
        {
            CreatedDate = DateTime.Now.ToLongTimeString();
        }

        public string ItemName { get { return Convert.ToString(base["_ItemName"]); } set { base["_ItemName"] = value; _UpdateModifiedDate(); } }
        public string Price { get { return Convert.ToString(base["_Price"]); } set { base["_Price"] = value; _UpdateModifiedDate(); } }
        public string CreatedDate { get { return Convert.ToString(base["_CreatedDate"]); } set { base["_CreatedDate"] = value; _UpdateModifiedDate(); } }
        public string ModifiedDate { get { return Convert.ToString(base["_ModifiedDate"]); } set { base["_ModifiedDate"] = value; } }

        private void _UpdateModifiedDate()
        {
            ModifiedDate = DateTime.Now.ToLongTimeString();
        }
    }

尝试自动设置修改日期和创建日期。但事实证明那些不适合放的地方。是否有任何其他可覆盖的方法来设置这些值?感谢。

1 个答案:

答案 0 :(得分:0)

使用OnRowChanged(或OnRowChanging)在DataTable中执行此操作。例如,

public class SpecialItemTable : DataTable
{

   protected override void OnRowChanged(DataRowChangeEventArgs e)
   {
      if (e.Action == DataRowAction.Add)
      {
         r.Row["CreatedDate"] = DateTime.Now;
      }
      else if (e.Action == DataRowAction.Change)
      {
         var time = DateTime.Now;
         // Check to prevent the cascaded row change events
         if ((time - (DateTime)e.Row["LastUpdated"]).TotalMilliseconds > 2)
         {
            e.Row["LastUpdated"] = time;
         }
      }
   }
}

(免责声明:未经测试的代码 - 仅提供一个想法)