gpt4 book ai didi

c# - 自动映射器、复杂属性和继承

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:12 24 4
gpt4 key购买 nike

我正在尝试让 AutoMapper 正常工作,但我真的坚持执行一项简单的任务。我在用户实体中定义了一个复杂类型:

[ComplexType]
public class CustomerProfile
{
public string FirstName { get; set; }
public string LastName { get; set; }
// ...
}

public class User
{
public long Id {get; set;}
public string Email { get; get; }
public CustomerProfile CustomerProfile { get; set; }
}

我有这样的 View 模型:

public class CustomerViewModel : CustomerProfile
{
public string Email { get; set; }
}

所以我只有 View 模型中的所有 CustomerProfile 属性以及电子邮件。

我想将 User 映射到 CustomerViewModel。我尝试了一切但实际上没有成功。即使这段代码也不起作用:

Mapper.CreateMap<CustomerProfile, CustomerViewModel>();

Automapper 只是拒绝映射任何东西。

如何映射?谢谢。

最佳答案

您可以使用 .ConstructUsingUser 实例创建一个 CustomerViewModel。然后,只要名称匹配,其余属性(例如,Email)将由 AutoMapper 自动映射:

Mapper.CreateMap<CustomerProfile, CustomerViewModel>();

Mapper.CreateMap<User, CustomerViewModel>()
.ConstructUsing(src => Mapper.Map<CustomerViewModel>(src.CustomerProfile));

示例: https://dotnetfiddle.net/RzpD4z


更新

要使 AssertConfigurationIsValid() 通过,您需要忽略手动映射的属性。您还需要从 CustomerProfileCustomerViewModel 映射中忽略 CustomerViewModel 上的 Email 属性,因为这将被采用由 User 处理 → CustomerViewModel 映射:

Mapper.CreateMap<CustomerProfile, CustomerViewModel>()
// Ignore Email since it's mapped by the User to CustomerViewModel mapping.
.ForMember(dest => dest.Email, opt => opt.Ignore());

Mapper.CreateMap<User, CustomerViewModel>()
.ConstructUsing(src => Mapper.Map<CustomerViewModel>(src.CustomerProfile))
// Ignore FirstName/LastName since they're mapped above using ConstructUsing.
.ForMember(dest => dest.FirstName, opt => opt.Ignore())
.ForMember(dest => dest.LastName, opt => opt.Ignore());

更新示例: https://dotnetfiddle.net/KitDiC

关于c# - 自动映射器、复杂属性和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26652756/

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