如何使用 CreateMissingTypeMaps 选项和 EF 代理类的手动映射?



我有一个情况,需要"同时"(或至少在相同的配置)使用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 上指出的这些方向重构了我的代码。

  1. 我的匿名类型检查有一个错误(我不应该使用 GetType)
  2. 必须忽略来自 System.Data.Entity.DynamicProxies 的对象

我重写的匿名个人资料类:

public class AnonymousProfile : Profile
{
public AnonymousProfile()
{
AddConditionalObjectMapper().Where((s, d) => 
s.IsAnonymousType() && s.Namespace != "System.Data.Entity.DynamicProxies");
}
}