[英]Automapper - ignore properties when nested as a child
I have two simple DTO defined that I'm passing to automapper v10.0.0我定义了两个简单的 DTO,我将它们传递给 automapper v10.0.0
class RequestDTO {
public int Id { get; set; }
// other properties
public IEnumerable<AssetDTO> Assets { get; set; }
}
class AssetDTO {
public int RequestId { get; set; }
// other properties
}
When I map an asset, it should show the RequestId
.当我映射资产时,它应该显示RequestId
。 That's working fine.这工作正常。 However, when I map a RequestDTO
, there's no reason for each asset to include the RequestId
as the Id
is already included via the RequestDTO
.但是,当我映射RequestDTO
,没有理由让每个资产都包含RequestId
因为Id
已经通过RequestDTO
包含了。
Is there a simple way to ignore the RequestId
when it's being mapped as a result of the parent request being mapped?当由于父请求被映射而被映射时,是否有一种简单的方法可以忽略RequestId
?
So if I'm just mapping an asset, I want所以如果我只是映射一个资产,我想要
{
"RequestId": 12,
"OtherProperty": ""
}
but if I'm mapping a request, I want:但如果我正在映射一个请求,我想要:
{
"Id": 12,
"Assets": [
{
"OtherProperty", ""
}
]
}
It is nothing about mapping, but about the shape of the data object.它与映射无关,而与数据对象的形状有关。 AssetDTO
is a class and it has the RequestId
property defined. AssetDTO
是一个类,它具有RequestId
定义的属性。 So, you cannot just expect to create an AssetDTO
object and not have the RequestId
property in it.因此,您不能只期望创建一个AssetDTO
对象而不在其中包含RequestId
属性。
Even if you try to ignore it in the mapping process, you will end up having RequestId
with a value of 0 (the default value for int
type).即使您尝试在映射过程中忽略它,最终RequestId
的值为 0( int
类型的默认值)。
The main purpose of DTOs is to create data objects in different shapes as required, and it's fairly common to create a multitude of DTOs to map from a single Model type. DTO 的主要目的是根据需要创建不同形状的数据对象,创建多个 DTO 以从单个模型类型映射是相当常见的。 Hence a solution to your problem would be using two different DTOs for mapping an Asset
type in two different scenarios -因此,您的问题的解决方案是使用两个不同的 DTO 在两个不同的场景中映射Asset
类型 -
class ChildAssetDTO
{
// other properties // no RequestId in this class
}
class AssetDTO : ChildAssetDTO
{
public int RequestId { get; set; } // only the RequestId in this class
}
class RequestDTO
{
public int Id { get; set; }
// other properties
public IEnumerable<ChildAssetDTO> Assets { get; set; }
}
Now you can use AssetDTO
to map an Asset
type, and AssetChildDTO
to map a Request
type.现在你可以使用AssetDTO
映射的Asset
类型, AssetChildDTO
来映射Request
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.