gpt4 book ai didi

AutoMapper 使用 UseValue 分配错误的值

转载 作者:行者123 更新时间:2023-12-01 12:37:58 25 4
gpt4 key购买 nike

我有以下代码片段:

Mapper.CreateMap<WorkOrderServiceTypeViewModel, WorkOrderServiceType>()
.ForMember(x => x.CompanyId, opt => opt.UseValue(_companyId));
Mapper.Map(model, workOrderServiceType);

当我运行它时,我的 watch 显示 _companyId 为 16,但在运行 Mapper.Map 后,workOrderServiceType.CompanyId 为 11。

我是不是做错了什么?

预计到达时间:.UseValue 似乎只执行一次。有什么想法吗?

enter image description here

作为引用,这是我的 2 个模型:

public class WorkOrderServiceTypeViewModel
{
public long Id { get; set; }
public string Name { get; set; }
public bool Residential { get; set; }
public bool Commercial { get; set; }
public bool Restoration { get; set; }
public bool Cleaning { get; set; }
public bool Storage { get; set; }
}

和数据库模型:

enter image description here

最佳答案

如果你想在映射上使用运行时值,你需要使用 AutoMapper 中的运行时值支持:

Mapper.CreateMap<WorkOrderServiceTypeViewModel, WorkOrderServiceType>()
.ForMember(x => x.CompanyId, opt => opt.ResolveUsing(res => res.Context.Options.Items["CompanyId"]));

然后在你的映射代码中:

Mapper.Map(model, workOrderServiceType, opt => opt.Items["CompanyId"] = _companyId);

您的配置应该是静态的并执行一次 - AutoMapper 假定了这一点。因此,为了将运行时值传递到映射中,我公开了一个字典,您可以将任何值填充到其中以在映射配置中使用。

关于AutoMapper 使用 UseValue 分配错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27869128/

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