我正在尝试映射2个对象,其中源对象具有几个惰性加载的属性,这些属性在每次使用时都会进入数据库。我无法更改这些对象。我只能更改映射。这是我到目前为止的内容。
CreateMap<CasePlan, CasePlanView>()
.ForMember(d => d.ProgramId, o => o.MapFrom(s => s.PrimaryReferral.ProgramRevisionId))
.ForMember(d => d.ClientName, o => o.MapFrom(s => s.PrimaryReferral.Client.FullName))
.ForMember(d => d.ClientId, o => o.MapFrom(s => s.PrimaryReferral.ClientId))
.ForMember(v => v.ClientBirthDate, o => o.MapFrom(s => s.PrimaryReferral.Client.BirthDate))
.ForMember(d => d.EnrollmentStartDate, o => o.MapFrom(s => s.PrimaryReferral.Enrollment.StartDate))
.ForMember(d => d.Age, o => o.MapFrom(s => s.PrimaryReferral.Client.BirthDate.ToAgeStringAtDate(s.Date).Replace("old", "")))
.ForMember(d => d.Program, o => o.MapFrom(s => s.PrimaryReferral.ProgramRevision.Program.Abbreviation))
.ForMember(d => d.PlacementWorker, o => o.MapFrom(s => s.PrimaryReferral.PlacementWorker.Name))
.ForMember(d => d.ReferralAgencyName, o => o.MapFrom(s => s.PrimaryReferral.ReferralSource.Name))
.ForMember(d => d.CourtStatus, o => o.MapFrom(s => s.PrimaryReferral.Client.LegalStatuses.FirstOrDefault() != null ? s.PrimaryReferral.Client.LegalStatuses.First().Status : null))
.ForMember(d => d.Approver, o => o.MapFrom(r => r.Approver.DisplayName))
.ForMember(d => d.ApproverId, o => o.MapFrom(s => s.ApproverId));
所有内容都正确映射,但是非常慢!每当我使用PrimarryReferral属性时,都会调用数据库。有没有一种方法可以指示AutoMapper缓存值并将其用于所有后续使用?
这项工作对您有用吗?
CreateMap<CasePlan, CasePlanView>()
.ConstructUsing((caseplan, b) => {
var client= a.PrimaryReferral.Client;
return new CasePlanView(){
ClientName= client.FullName,
ClientBirthDate= client.BirthDate //and so on
}
});
这样,至少对于a.PrimaryReferral.Client
的属性,您将不会多次访问数据库。但是,您需要为每个具有属性的对象访问数据库。
解决此问题的一种方法是使用CasePlan
源中的include消除对延迟加载的需求。我不知道您是否能够做到这一点,但这是我的建议。
[我不推荐的另一种方法是将DatabaseContext
(或存储库)注入到映射器,并通过使用CasePlan
的PK,再次从数据库中获得CasePlan
。 (这基本上不会从CasePlan
对象映射,但会从db重新获取该对象。因此,如果CasePlan
对象中的数据与db中的数据不同,则会引起其他问题)。 >