回答:CreateMissingTypeMaps
必须设置为 true
才能使动态映射工作。
public IEnumerable<T> GetDummies<T>(IEnumerable<dynamic> dummies)
{
var config =
new MapperConfiguration(c => { c.CreateMissingTypeMaps = true; });
IMapper mapper = config.CreateMapper();
return dummies.Select(mapper.Map<T>).ToList();
}
我有围绕 Entity Framework 的包装器来执行对数据库的查询。我想让用户只选择所需的属性,但保留实体类型的结果。
这是伪代码(没有使用 EF,但有同样的问题)
class Program
{
static void Main(string[] args)
{
var dummies = new[]
{
new DummyContainer
{
Name = "First",
Description = "First dummy",
DummyNumbers = new List<int> { 1, 2, 3 },
Foo = new FooThingy { Title = "Foo thingy" }
}
};
var smallDummies = dummies.Select(d => new { d.Name }).ToList();
List<DummyContainer> fullDummies = smallDummies.Select(Mapper.Map<DummyContainer>).ToList();
Debugger.Break();
}
}
class DummyContainer
{
public string Name { get; set; }
public string Description { get; set; }
public ICollection<int> DummyNumbers { get; set; }
public FooThingy Foo { get; set; }
}
class FooThingy
{
public string Title { get; set; }
}
获取此异常:
Missing type map configuration or unsupported mapping.
Mapping types:
<>f__AnonymousType0`1 -> DummyContainer
<>f__AnonymousType0`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] -> AutoMapperWithGenerics.DummyContainer
Destination path:
DummyContainer
Source value:
{ Name = First }
我有点卡在这里,因为文档指出 AutoMapper 使用属性名称映射回对象:Dynamic and ExpandoObject Mapping .
请注意上面的代码只是示例。在我的应用程序中,事情变得有点疯狂,因为我实际上在使用泛型,例如
Mapper.Map<TEntity>
...它应该保持这种状态——我不知道使用的是什么实体类型。我的期望只是:将属性映射到现有类型,如果缺少,则设置 default(T)
。
编辑:我尝试将映射器从dynamic
指定为T
,这里几乎是完整的代码:
class Program
{
static void Main(string[] args)
{
// ...
var dumminator = new DummyService();
IEnumerable<DummyContainer> bigDummies = dumminator.GetDummies<DummyContainer>(smallDummies);
Debugger.Break();
}
}
class DummyService
{
public IEnumerable<T> GetDummies<T>(IEnumerable<dynamic> dummies)
{
var config = new MapperConfiguration(c => c.CreateMap<dynamic, T>());
IMapper mapper = config.CreateMapper();
return dummies.Select(mapper.Map<T>).ToList();
}
}
...这不会因异常而死,但是结果非常空(所有属性都有 default
值。
最佳答案
您可以全局配置它,而不是弃用的 DynamicMap
。
var config = new MapperConfiguration(cfg => cfg.CreateMissingTypeMaps = true);
Reference到维基。
关于c# - 具有动态类型 : Missing type map configuration or unsupported mapping 的 AutoMapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36745756/