gpt4 book ai didi

.net - 如何映射嵌套类型

转载 作者:行者123 更新时间:2023-12-05 04:16:31 25 4
gpt4 key购买 nike

我在进行三级映射时遇到了问题。类(class)如下:

public class Company {
public Contact MainContact { get; private set; }
}


public class Contact {
public PersonsName ContactName { get; private set; }
}

public class PersonsName {
public String FirstName { get; private set; }
public String LastName { get; private set; }

}

public class CreateCompanyViewModel {
[Required]
[MaxLength(25, ErrorMessage = "Only 25 characters are allowed.")]
[Display(Name = "First Name")]
public String FirstName { get; set; }

[Required]
[MaxLength(25, ErrorMessage = "Only 25 characters are allowed.")]
[Display(Name = "Last Name")]
public String LastName { get; set; }
}

我尝试了以下但没有成功:

Mapper.CreateMap<CreateCompanyViewModel, PersonsName>()
.ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.FirstName))
.ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.LastName));

Mapper.CreateMap<Contact, PersonsName>()
.ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.ContactName.FirstName))
.ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.ContactName.LastName));

Mapper.CreateMap<CreateCompanyViewModel, Company>()
.ForMember(dest => dest.MainContact.ContactName.FirstName, opt => opt.MapFrom(src => src.FirstName))
.ForMember(dest => dest.MainContact.ContactName.FirstName, opt => opt.MapFrom(src => src.LastName));

我得到的错误信息是:

表达式 'dest => dest.MainContact.ContactName.FirstName' 必须解析为顶级成员,而不是任何子对象的属性。改为对子类型或 AfterMap 选项使用自定义解析器。参数名称:lambdaExpression

最佳答案

您可以使用以下配置:

/* Innermost mapping */
Mapper.CreateMap<CreateCompanyViewModel, PersonsName>();
// You don't need the individual member mappings since the names match.

/* Second-level */
Mapper.CreateMap<CreateCompanyViewModel, Contact>()
.ForMember(dest => dest.ContactName, opt => opt.MapFrom(src => src));

/* Top level */
Mapper.CreateMap<CreateCompanyViewModel, Company>()
.ForMember(dest => dest.MainContact, opt => opt.MapFrom(src => src));

想法是您也使用源类型 (CreateCompanyViewModel) 作为嵌套类型的源。您可以使用 ForMember 中的 MapFrom(src => src) 调用来完成此操作。

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

由于 src => src 看起来有点奇怪,您可以创建一个扩展方法,使您的操作更加直接:

public static class AutoMapperExtensions
{
public static void MapFromSelf<TSourceType>(
this IMemberConfigurationExpression<TSourceType> expression)
{
expression.MapFrom(s => s);
}
}

用法:

Mapper.CreateMap<CreateCompanyViewModel, Contact>()
.ForMember(dest => dest.ContactName, opt => opt.MapFromSelf());

Mapper.CreateMap<CreateCompanyViewModel, Company>()
.ForMember(dest => dest.MainContact, opt => opt.MapFromSelf());

关于.net - 如何映射嵌套类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27270160/

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