Automapper项目使用 [英] Automapper Project using
问题描述
我当前在后端使用automapper来将对象映射到模型. 我最近决定使用以下代码来处理我所有的时区转换:
I am currently using automapper in my backend to map objects to models. I recently decided to use the following code to handle all my timezone conversions:
cfg.CreateMap<DateTime?, DateTime?>()
.ProjectUsing(i => DbFunctions.AddHours(i, offset.Hours));
cfg.CreateMap<DateTime, DateTime>()
.ProjectUsing(i => DbFunctions.AddHours(i, offset.Hours).Value);
Object.ProjectTo<ObjectModel>().SingleOrDefault();
然后正常工作,并映射对象并转换时区
then it works fine and the object is mapped and timezone converted
但是,当我在业务层中使用以下代码进行单个对象映射时:
However when i am using the following code in my business layer to do a single object mapping:
Mapper.Map<Object, ObjectModel>(singleRecord);
它给出一个错误: 此函数只能从LINQ到Entities调用.
It Gives an error : This function can only be invoked from LINQ to Entities.
堆栈跟踪:
at System.Data.Entity.DbFunctions.AddHours(Nullable`1 timeValue, Nullable`1 addValue)
at lambda_method(Closure , DateTime , DateTime , ResolutionContext )
at AutoMapper.ResolutionContext.Map[TSource,TDestination](TSource source, TDestination destination)
at lambda_method(Closure , Inventory , InventoryModel , ResolutionContext )
Mapper.Map对于在特定情况下使用非常重要,我也不想投影单个记录.
Mapper.Map is important to use in specific scenarios and i also don't want to project single records.
有办法解决吗?
推荐答案
默认情况下,AutoMapper将通过编译传递给ProjectUsing
并由ProjectTo
,因为通常就足够了并且可以正常工作.但是没有EF规范功能.
By default AutoMapper will build a mapping Func<TSource, TDestination>>
to be used by Map
method by compiling the Expression<TFunc<TSource, TDestionation>>
passed to ProjectUsing
and used by ProjectTo
, because usually it's enough and works. But not with EF canonical functions.
您可以通过显式提供ProjectUsing
和ConvertUsing
来指定与Map
方法一起使用的另一种转换来覆盖该行为:
You could override that behavior by specifying a different conversion to be used with Map
method by providing explicitly both ProjectUsing
and ConvertUsing
:
var map1 = cfg.CreateMap<DateTime?, DateTime?>();
map1.ProjectUsing(i => DbFunctions.AddHours(i, offset.Hours));
map1.ConvertUsing(i => i?.AddHours(offset.Hours));
var map2 = cfg.CreateMap<DateTime, DateTime>();
map2.ProjectUsing(i => DbFunctions.AddHours(i, offset.Hours).Value);
map2.ConvertUsing(i => i.AddHours(offset.Hours));
这篇关于Automapper项目使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!