我有一种情况需要“同时”(或至少在相同的配置)使用 CreateMissingTypeMaps 和手动映射。
场景:使用配置文件手动映射域和视图模型类。 CreateMissingTypeMaps 属性是必要的,因为我有一个反腐败层来访问返回匿名对象的遗留系统。
问题是,当手动映射设置为 true 时,它的映射会被 CreateMissingTypeMaps 选项覆盖,而当它设置为 false 时,我无法映射匿名对象。
我尝试在 MapperConfiguration 内、配置文件内以及具有映射条件的配置文件内设置 CreateMissingTypeMaps,但都失败了。
下面的代码是我尝试执行的条件配置文件,该配置文件应仅应用于匿名对象。
public class AnonymousProfile : Profile
{
public AnonymousProfile()
{
AddConditionalObjectMapper().Where((s, d) => s.GetType().IsAnonymousType());
CreateMissingTypeMaps = true;
}
}
// inside my MapperConfiguration
cfg.AddProfile(new AnonymousProfile()); // also tried cfg.CreateMissingTypeMaps = true;
[编辑:] 最初的问题没有提到 EF,但我发现它的代理类是问题的一部分。
我按照 Tyler 在 Github 上指出的这些方向重构了我的代码。
我重写的 AnonymousProfile 类:
public class AnonymousProfile : Profile
{
public AnonymousProfile()
{
AddConditionalObjectMapper().Where((s, d) =>
s.IsAnonymousType() && s.Namespace != "System.Data.Entity.DynamicProxies");
}
}