使用自动映射器映射嵌套对象

编程入门 行业动态 更新时间:2024-10-27 13:21:14
本文介绍了使用自动映射器映射嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个Customer EF POCO类,其中包含对Address表的引用.

I have a Customers EF POCO class which contains a reference to the Address table.

以下代码似乎有效,但是我不确定这是最干净的方法.有没有更好的方法可以仅使用一个Map调用来映射它?

The following code seems to work, but I'm not sure it's the cleanest way to do this. Is there a better way to map this using only a single Map call?

[HttpGet] public ActionResult Details(string ID) { BusinessLogic.Customers blCustomers = new BusinessLogic.Customers("CSU"); DataModels.Customer customer = blCustomers.GetCustomer(ID); CustomerDetailsViewModel model = new CustomerDetailsViewModel(); Mapper.CreateMap<DataModels.Customer, CustomerDetailsViewModel>(); Mapper.CreateMap<DataModels.Address, CustomerDetailsViewModel>(); Mapper.Map(customer, model); Mapper.Map(customer.Address, model); return View(model); }

推荐答案

这取决于您的CustomerDetailsViewModel外观.例如,如果您的Address类看起来像这样:

It depends on what your CustomerDetailsViewModel looks like. For example, if your Address class looks something like this:

public class Address { public string Street { get; set; } public string City { get; set; } }

和CustomerDetailsViewModel包含遵循以下约定的属性:

and CustomerDetailsViewModel contains properties following this convention:

在AutoMapper中配置源/目标类型对时, 配置器尝试匹配源上的属性和方法 输入目标类型上的属性.如果是关于 目标类型键入属性,方法或以"Get"为前缀的方法 源类型上不存在,AutoMapper拆分目标 成员名称转换成单个单词(按照PascalCase约定).

When you configure a source/destination type pair in AutoMapper, the configurator attempts to match properties and methods on the source type to properties on the destination type. If for any property on the destination type a property, method, or a method prefixed with "Get" does not exist on the source type, AutoMapper splits the destination member name into individual words (by PascalCase conventions).

(来源:平化)

然后,如果CustomerDetailsViewModel具有属性:

public string AddressStreet { get; set; } public string AddressCity { get; set; }

只需一个从Customer到CustomerDetailsViewModel的映射即可.对于不符合该约定的成员,可以使用ForMember.

Just one mapping from Customer to CustomerDetailsViewModel will work. For members that don't match that convention, you could use ForMember.

对于每个单个地址属性,您也始终可以使用ForMember:

You can always use ForMember for every single address property as well:

Mapper.CreateMap<DataModels.Customer, CustomerDetailsViewModel>() .ForMember(dest => dest.Street, opt => opt.MapFrom(src => src.Address.Street)); /* etc, for other address properties */

就我个人而言,我不会太担心两次致电.Map.至少以这种方式,很明显,Address和Customer属性都已被映射.

Personally, I wouldn't be too worried about calling .Map twice. At least that way it's very clear that both Address and Customer properties are being mapped.

更多推荐

使用自动映射器映射嵌套对象

本文发布于:2023-11-04 12:05:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557890.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   对象   映射器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!