首页 > 解决方案 > EF 6.4 DbCommandInterceptor 相关 C#

问题描述

我目前正在尝试更改 DbCommandInterceptor 中的参数,以便能够在保存之前将日期时间转换为 UTC。在某些情况下,我不想根据实体属性转换参数。

例子:

public class UtcReadInterceptor : DbCommandInterceptor
{
    public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        foreach (DbParameter p in command.Parameters)
        {
            if (p.DbType != DbType.DateTime2 || ShouldSkip(p)) { continue; }

            var date = p.Value as DateTime?;

            if (!date.HasValue) { continue; }

            p.Value = date.Value.ToUniversalTime()
        }

        base.ReaderExecuting(command, interceptionContext);
    }
} 

private bool ShouldSkip(DbParameter p)
{
   // Look up the parameter in EF metadata and choose ignore or let through.
}

我正在寻找的是某种方式来了解给定字段是否不应转换为 UTC。我需要以某种方式在上下文中查找它是哪个字段(以及在哪个实体上),或者以某种方式在某种查找中标记它以便能够知道是否跳过它。

有谁知道如何将参数与 EF 实体上的字段相关联或以某种方式从 EF 更改参数以知道在将日期时间参数转换为 UTC 时是否可以跳过它?

标签: c#entity-framework

解决方案


我一直无法找到答案,并且在阅读了 EF6 代码之后,似乎几乎没有什么可以传递给基于实体字段的参数。该代码似乎只有给定字段类型的默认值并使用它们。

我可以分离列类型的唯一方法是将一种类型设置为 DateTimeOffset,将另一种类型设置为 DateTime。作为参数 db 类型 DateTime 和 DateTime2


推荐阅读