[英]AutoMapper with dynamic type: Missing type map configuration or unsupported mapping
答:必须将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和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);
引用维基。
您需要使用Mapper.DynamicMap<T>
而不是Mapper.Map<T>
从动态或匿名类进行映射
List<DummyContainer> fullDummies = smallDummies.Select(Mapper.DynamicMap<DummyContainer>).ToList();
您好类似的答案,但不要忘记在您的类上有一个私有构造函数,并且不要不验证内联映射。
public class Player
{
private Player() {}.....
}
var mapper = new MapperConfiguration(cfg =>
{
cfg.ValidateInlineMaps = false;
cfg.CreateMissingTypeMaps = true;
}).CreateMapper();
var player= mapper.Map<Player>(anonymousData);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.