1

在我们必须使用的数据库(即 DB2)中,有些字段存储为字符,但实际上是其他对象,最常见的是底层应用程序存储日期和时间的自定义方式。例如:

[Table]
public class ExampleTable {
    // This is stored in the DB as a char in the format: 2016-01-11-11.39.53.492000
    [Column(Name = "WTIMESTAMP")] public string WriteTimestamp { get; set; }
}

有没有办法告诉 linq2db 在从数据库转换到/从数据库时使用的转换方法,这也将允许我们将这些属性作为我们想要的对象(例如,C# DateTime 对象)访问,但又被保存回正确的格式?

我想到的一件事是:

[Table]
public class ExampleTable {

    public DateTime WriteTimestamp { get; set; }

    // This is stored in the DB as a char in the format: 2016-01-11-11.39.53.492000
    [Column(Name = "WTIMESTAMP")] public string WriteTimestampRaw 
    { 
        get {
            return ConvertWriteTimestampToDb2Format(WriteTimestamp);
        } 
        set {
            WriteTimestamp = ConvertWriteTimestampToDateTime(value);    
        }
    }
}

然后我们访问 WriteTimestamp,但 linq2db 在查询中使用 WriteTimestampRaw。

但是,我不确定这是最好的还是唯一的选择。提前致谢。

4

2 回答 2

2

linq2db好吧......在我发布答案后,我注意到你说的是实体框架而不是实体框架。不过,也许它仍然会给您一些想法。


我之前对 Entity Framework 所做的(虽然不是专门针对 DB2,但我认为它应该仍然可以工作)是使用此答案中提供的代码来允许将私有属性映射到数据库列。然后,我有一些类似于你的代码的东西,除了 getter 和 setter 是相反的:

[Table("ExampleTable")]
public class ExampleTable
{
    [NotMapped]
    public DateTime WriteTimestamp
    {
        get
        {
            var db2Tstamp = DB2TimeStamp.Parse(WriteTimestampRaw);
            return db2Tstamp.Value;
        }
        set
        {
            var db2Tstamp = new DB2TimeStamp(value);
            WriteTimestampRaw = db2Tstamp.ToString();
        }
    }

    // This is stored in the DB as a char in the format: 2016-01-11-11.39.53.492000
    [Column("WTIMESTAMP")]
    private string WriteTimestampRaw { get; set; }
}

我使用DB2TimeStamp该类来处理字符串和 DateTime 值之间的转换,但是您可以按照自己的喜好进行操作。

于 2016-01-11T20:00:11.677 回答
0

您可以使用 MappingSchema.SetConverter 方法在客户端设置特定类型之间的转换。或 MappingSchema.SetConverterExpression 创建转换器作为查询树的一部分。

于 2016-01-15T03:12:14.377 回答