简体   繁体   English

使用 ConvertUsing 到 map 并使用 SqlFunctions 进行投影

[英]Using ConvertUsing to map and to project with SqlFunctions

I am upgrading a .NET Framework project from Automapper 4.1.1 to Automapper 10.0.0 and I am encountering a problem that I am unable to resolve.我正在将一个 .NET Framework 项目从 Automapper 4.1.1 升级到 Automapper 10.0.0,我遇到了一个我无法解决的问题。 I see that ConvertUsing and ProjectUsing have been unified, but somehow I have to be able to tell if a Mapping or a Project is being done.我看到 ConvertUsing 和 ProjectUsing 已经统一,但不知何故我必须能够判断是否正在完成映射或项目。 I have a configuration so that it is applied generically when changing a DateTime to an int so that it transforms by calculating the number of minutes.我有一个配置,以便在将 DateTime 更改为 int 时普遍应用它,以便它通过计算分钟数进行转换。 I need to use SqlFunctions to do the conversion but only when we are projecting, when we are mapping it must be done through a simple transformation.我需要使用 SqlFunctions 进行转换,但仅当我们进行投影时,当我们进行映射时,才必须通过简单的转换来完成。 How can you do this if you can now only have one ConvertUsing?如果你现在只能有一个 ConvertUsing,你怎么能做到这一点?

       CreateMap<DateTime?, int>().ConvertUsing(x => x.HasValue ? System.Data.Entity.SqlServer.SqlFunctions.DatePart("HOUR", x.Value).Value * 60 + System.Data.Entity.SqlServer.SqlFunctions.DatePart("MINUTE", x.Value).Value : 0); CreateMap<DateTime, int>().ConvertUsing(x => System.Data.Entity.SqlServer.SqlFunctions.DatePart("HOUR", x).Value * 60 + System.Data.Entity.SqlServer.SqlFunctions.DatePart("MINUTE", x).Value); CreateMap<DateTime?, int>().ConvertUsing(x => Convert.ToInt32(x.HasValue ? x.Value.TimeOfDay.TotalMinutes : 0)); CreateMap<DateTime, int>().ConvertUsing(x => Convert.ToInt32(x.TimeOfDay.TotalMinutes));

I tried using ProjectUsing or looking for a parameter inside ConvertUsing that tells me if I'm converting an IQueryable but it doesn't seem to exist我尝试使用 ProjectUsing 或在 ConvertUsing 中寻找一个参数,它告诉我是否正在转换 IQueryable 但它似乎不存在

You can create custom DB function (using eg CodeFirstFunctions or EntityFramework.Functions package that allows creating custom functions) and provide body of this function (example):您可以创建自定义 DB function(使用例如 CodeFirstFunctions 或 EntityFramework.Functions package 允许创建自定义函数)并提供此 function 的正文(示例):

[Function(FunctionType.ComposableScalarValuedFunction, nameof(SecondsDiff), Schema = "dbo")]
[return: Parameter(DbType = "int")]
public static int? SecondsDiff([Parameter(DbType = "date")] DateTime? date1, [Parameter(DbType = "date")] DateTime? date2)
{
    if (date1 == null || date2 == null)
    {
        return null;
    }

    DateTime a = date1.Value;
    DateTime b = date2.Value;

    if (a >= b)
    {
        return (int?)(b - a).TotalSeconds;
    }

    return -(int?)(a - b).TotalSeconds;
}

It will work in both modes.它将在两种模式下工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM