C# 映射时缓存嵌套属性
我试图映射两个对象,其中源对象有两个延迟加载的属性,它们在任何时候被使用时都会转到DB。我无法更改这些对象。我只能更改映射。这是我到目前为止所拥有的C# 映射时缓存嵌套属性,c#,automapper,C#,Automapper,我试图映射两个对象,其中源对象有两个延迟加载的属性,它们在任何时候被使用时都会转到DB。我无法更改这些对象。我只能更改映射。这是我到目前为止所拥有的 CreateMap<CasePlan, CasePlanView>() .ForMember(d => d.ProgramId, o => o.MapFrom(s => s.PrimaryReferral.ProgramRevisionId)) .ForM
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属性时,就会调用DB。是否有方法指示AutoMapper缓存该值并将其用于所有后续用途 这对你有用吗
CreateMap<CasePlan, CasePlanView>()
.ConstructUsing((caseplan, b) => {
var client= a.PrimaryReferral.Client;
return new CasePlanView(){
ClientName= client.FullName,
ClientBirthDate= client.BirthDate //and so on
}
});
通过这种方式,您至少不会针对.PrimaryReferral.Client的属性多次访问数据库。
但是,您需要为每个具有属性的对象访问数据库
解决这一问题的一种方法是在CasePlan的源代码处使用include消除延迟加载的需要。我不知道你是否能做到,但那将是我的建议
我不推荐的另一种方法是将DatabaseContextor存储库注入映射器,并通过使用CasePlan的PK,再次从数据库中获取CasePlan。这实际上不会从CasePlan对象映射,而是从db重新获取对象。因此,如果来自CasePlan对象的数据与数据库中的数据不同,则会导致其他问题。除了映射代码之外,如果您向我们展示了正在映射的模型,可能会有所帮助。