所以我有一个运行良好的移动服务,并希望添加DTO'符号。 我使用AutoMapper在我的模型和DTO模型之间进行映射,但是数据库的复杂性和我想要的结果迫使我使用自定义解析器,而这反过来会抛出null异常。
具体 - Mapper初始化
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Contact, MobileContact>()
.ForMember(mobcont => mobcont.Favorite, map => map.ResolveUsing<ContactResolver>());//.UseValue(true));//
cfg.CreateMap<MobileContact, Contact>();
});
我的自定义解析器
public class ContactResolver : ValueResolver<Contact, bool>
{
protected override bool ResolveCore(Contact a)
{
return true;
}
}
编辑:收藏当然是一个布尔
如果我不使用自定义解析器并使用.UseValue(true)它可以正常工作
虽然如上所示使用自定义解析程序的常见get请求会引发以下异常:
Exception=System.NullReferenceException: Object reference not set to an instance of an object.
at AutoMapper.QueryableExtensions.Extensions.ResolveExpression(PropertyMap propertyMap, Type currentType, Expression instanceParameter)
at AutoMapper.QueryableExtensions.Extensions.CreateMemberBindings(IMappingEngine mappingEngine, TypePair typePair, TypeMap typeMap, Expression instanceParameter, IDictionary`2 typePairCount)
at AutoMapper.QueryableExtensions.Extensions.CreateMapExpression(IMappingEngine mappingEngine, TypePair typePair, Expression instanceParameter, IDictionary`2 typePairCount)
at AutoMapper.QueryableExtensions.Extensions.CreateMapExpression(IMappingEngine mappingEngine, TypePair typePair, IDictionary`2 typePairCount)
at AutoMapper.QueryableExtensions.Extensions.<>c__DisplayClass1`2.<CreateMapExpression>b__0(TypePair tp)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at AutoMapper.Internal.DictionaryFactoryOverride.ConcurrentDictionaryImpl`2.GetOrAdd(TKey key, Func`2 valueFactory)
at AutoMapper.QueryableExtensions.Extensions.CreateMapExpression[TSource,TDestination](IMappingEngine mappingEngine)
at AutoMapper.QueryableExtensions.ProjectionExpression`1.To[TResult]()
at Microsoft.WindowsAzure.Mobile.Service.MappedEntityDomainManager`2.Query()
at azmobtestService.Models.MobileContactDomainManager.Query() in c:\Users\n.atlas\Source\Repos\JPhoneBook\Service\azmobtestService\Models\MobileContactDomainManager.cs:line 104
at Microsoft.WindowsAzure.Mobile.Service.TableController`1.Query(), Id=75849f58-ccb0-4a6b-8a77-491f13fcb717, Category='App.Controllers.Tables'
答案 0 :(得分:0)
如果您所做的一切都是在所有情况下都将喜爱解析为真(这是不对的,但这是您提供的代码,因此我会使用它),那么您的映射器可以只是.ForMember(mobcont => mobcont.Favorite, expression => expression.MapFrom(source => true));
如果您正在寻找正常价值的解析器,我会选择这样的ITypeConverter:
public class ContactToMobileContactTypeConverter : ITypeConverter<Contact, MobileContact>
{
public MobileContact Convert(ResolutionContext context)
{
var contact = (Contact)context.SourceValue;
var mobileContact = new MobileContact();
if(contact != null) {
//database query
//assign values
}
return mobileContact;
}
}