gpt4 book ai didi

c# - AutoMapper新增的IValueResolver如何使用?

转载 作者:IT王子 更新时间:2023-10-29 04:50:04 24 4
gpt4 key购买 nike

我不知道如何使用新的 IValueResolver新版AutoMapper中的界面。可能是我在之前版本的AutoMapper中使用不当...

我有很多模型类,其中一些是使用 sqlmetal 从多个数据库服务器上的多个数据库生成的。

其中一些类有一个字符串属性,PublicationCode ,它标识订阅、报价、发票或其他任何内容属于哪个出版物。

发布可以存在于两个系统(旧系统和新系统)中的任何一个中,因此我在目标模型类上有一个 bool 属性,它告诉发布是在旧系统还是新系统中。

使用旧版本(<5?)的 AutoMapper,我使用了 ValueResolver<string, bool>花了PublicationCode作为输入参数,并返回一个 bool指示发布位置(旧系统或新系统)。

随着 AutoMapper 的新版本(5+?),这似乎不再可能了。新的 IValueResolver 需要对我拥有的每个源模型和目标模型的组合进行独特的实现,其中 src.PublicationCode需要解析为 dst.IsInNewSystem .

我只是想以错误的方式使用值解析器吗?有没有更好的办法?我想使用解析器的主要原因是我更愿意将服务注入(inject)构造函数,而不必使用 DependencyResolver以及代码中的类似内容(我正在使用 Autofac)。

目前我的使用方式如下:

// Class from Linq-to-SQL, non-related properties removed.
public class FindCustomerServiceSellOffers {
public string PublicationCode { get; set; }
}

这是我拥有的几个数据模型类之一,其中包含一个 PublicationCode 属性)。这个特定的类映射到这个 View 模型:

public class SalesPitchViewModel {
public bool IsInNewSystem { get; set; }
}

这两个类的映射定义是(其中expression是一个IProfileExpression),去掉了不相关的映射:

expression.CreateMap<FindCustomerServiceSellOffers, SalesPitchViewModel>()
.ForMember(d => d.IsInNewSystem, o => o.ResolveUsing<PublicationSystemResolver>().FromMember(s => s.PublicationCode));

解析器:

public class PublicationSystemResolver : ValueResolver<string, bool>
{
private readonly PublicationService _publicationService;
public PublicationSystemResolver(PublicationService publicationService)
{
_publicationService = publicationService;
}

protected override bool ResolveCore(string publicationCode)
{
return _publicationService.IsInNewSystem(publicationCode);
}
}

以及映射器的使用:

var result = context.FindCustomerServiceSellOffers.Where(o => someCriteria).Select(_mapper.Map<SalesPitchViewModel>).ToList();

最佳答案

您可以通过实现 IMemberValueResolver<object, object, string, bool> 创建一个更通用的值解析器并在您的映射配置中使用它。您可以像以前一样提供源属性解析函数:

public class PublicationSystemResolver : IMemberValueResolver<object, object, string, bool>
{
private readonly PublicationService _publicationService;

public PublicationSystemResolver(PublicationService publicationService)
{
this._publicationService = publicationService;
}

public bool Resolve(object source, object destination, string sourceMember, bool destMember, ResolutionContext context)
{
return _publicationService.IsInNewSystem(sourceMember);
}
}



cfg.CreateMap<FindCustomerServiceSellOffers, SalesPitchViewModel>()
.ForMember(dest => dest.IsInNewSystem,
src => src.ResolveUsing<PublicationSystemResolver, string>(s => s.PublicationCode));

关于c# - AutoMapper新增的IValueResolver如何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38306461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com