【问题标题】:EntityFramework: Access database-column using user defined TypeEntityFramework:使用用户定义的类型访问数据库列
【发布时间】:2011-03-03 13:21:54
【问题描述】:

我“继承”了一个旧数据库,其中日期存储为 Int32 值(时间也是如此,但对于此示例而言,日期就足够了),即 20090101 表示 2009 年 1 月 1 日。 我无法更改此数据库的架构,因为旧程序仍在访问它。
但是,我想编写一个使用 EF 作为 O/R-M 的新程序。
现在我很想在我的模型中有 DateTime-Values。

有没有办法编写自定义类型并将其用作 EF 模型中的类型。

类似于“OldDate”类型
具有属性:
数据库值:Int23
值:DateTime(指定日期部分,而时间部分始终为 0:00:00)

EF-Model 可以实现这样的事情吗?

编辑:
我想我找到了我想要的东西——但是在 NHibernate 中,所以我会改写:
EF 是否可以使用 NHIbernates IUserType 之类的东西?

【问题讨论】:

    标签: database entity-framework types mapping


    【解决方案1】:

    ComlexType 可以解决这个问题。我创建了一个类型LeagcyDate,它将int 值存储在DbData 属性中,并添加了与Date 的隐式转换。这种方法似乎相当易于管理。由于模型设计器中支持 EF4 复杂类型,因此添加一个不再调用篡改 edmx。

    我在部分类中完成的隐式转换如下:

        public partial class LegacyDate
        {
          public static implicit operator DateTime?(LegacyDate value)
          {
              return LegacyDateConverter.ToDate(value.DbData);
          }
    
          public static implicit operator LegacyDate(DateTime? value)
          {
              return new LegacyDate { DbData = LegacyDateConverter.ToLegacyDate(value) };
          }
       }
    
        internal static class LegacyDateConverter
        {
            public static DateTime? ToDate(int data)
            {
                if (data == 0) return null;
                int year = data/10000;
                int month = (data%10000)/100;
                int day = data/1000000;
                DateTime date;
    
                try
                {
                    date = new DateTime(year, month, day);
                }
                catch (Exception e)
                {
                    throw new ArgumentException(String.Format(
                        "Value {0} kan not be converted to DateTime", data), e);
                }
                return date;
            }
    
            public static int ToLegacyDate(DateTime? value)
            {
                int dateInt = 0;
                if (value.HasValue)
                {
                    dateInt =
                    value.Value.Year*10000 + value.Value.Month*100 + value.Value.Day;
                }
                return dateInt;            
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 2021-10-31
      相关资源
      最近更新 更多