【问题标题】:How to properly implement IHydratable interface in DNN?如何在 DNN 中正确实现 IHydratable 接口?
【发布时间】:2011-04-04 11:45:17
【问题描述】:

升级到DNN 5.5.0 后,我们必须在所有业务对象上实施IHydratable

这个想法一开始似乎是个不错的方法,但在玩过IHydratable 之后,我就不太确定了。

有两种可能:

  1. 我做错了
  2. IHydratable 强制您使用 select * 构建所有查询

商业案例:

  • 我的第一个存储过程返回 BgIdBgShortDesc
  • 我的第二个存储过程返回 BgIdBgReportedUser

我的IHydratable 实现如下所示:

public class Bug : IHydratable
{ 
  public int BgId { get; set; }
  public string BgShortDesc { get; set; }
  public int BgReportedUser { get; set; }
  public DateTime BgReportedDate { get; set; }

  public Bug() { }

  public int KeyID
  {
    get { return BgId; }
    set { BgId = value; }
  }

  public void Fill(IDataReader dr)
  {
    BgId = Convert.ToInt32(Null.SetNull(dr["BgId"], BgId));
    BgShortDesc = Convert.ToString(Null.SetNull(dr["BgShortDesc"], BgShortDesc));
    BgReportedUser = Convert.ToInt32(Null.SetNull(dr["BgReportedUser"], BgReportedUser));
    BgReportedDate = Convert.ToDateTime(Null.SetNull(dr["BgReportedDate"], BgReportedDate));
  }
}

fill 方法将在上述任何存储过程中抛出IndexOutOfRangeException,因为并非所有字段都以IDataReader 返回。

解决此问题的简单方法是在所有存储过程中使用select *,但这不是一个好习惯。

在这种情况下实现IHydratable 的正确方法是什么?

P.S.请记住,我的示例过于简单化了,无法理解。

【问题讨论】:

    标签: interface dotnetnuke dotnetnuke-5


    【解决方案1】:

    我在another forum得到了一个可行的答案

    建议如下:

        public void Fill(IDataReader dr)
        {
                if (dr.ColumnExists("BgId"))
                {
                  BgId = Convert.ToInt32(Null.SetNull(dr["BgId"], BgId));
                }
                //do the above for all the properties
        }
    

    编辑:

    借助 SO(@JamesEggers@Chad Grant)上的这 2 个答案,通过在 IDataReader 上编写扩展方法找到了一种更好的方法

        /// <summary>
        /// Check if the column exists in the datareader before accessing its value
        /// </summary>
        /// <param name="reader">DataReader</param>
        /// <param name="columnName">Column name</param>
        /// <returns>True if column exists, false if not</returns>
        public static bool ColumnExists(this IDataReader reader, string columnName)
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                if (reader.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
                {
                    return true;
                }
            }
    
            return false;
        }
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-15
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      相关资源
      最近更新 更多