为了让开发ASP.Net Core 2.2 API前端的开发人员更加轻松,我希望他们接收到“null”值而不是Guid.Empty值(在.net core中定义为“00000000-0000-0000-0000-000000000000”)。
通过创建以下数据传输对象,实现这种行为并不复杂:
为了避免无限的HasValue()检查。然而,我认为更具信息性和一致性的做法是返回这个(参见customerId):
比这更好:
通过创建以下数据传输对象,实现这种行为并不复杂:
public class ExampleDto
{
public Guid? Id { get; set; }
}
然后像这样进行映射
public static void MapExampleEntity(this AutoMapperProfile profile)
{
profile.CreateMap<ExampleEntity, ExampleDto>()
.ForMember(dto => dto.Id, o => o.MapFrom(e => e.Id == Guid.Empty ? null : e.Id);
}
然而,对于我认为控制器应该能够通过某些配置处理的任务而言,这是大量的代码重复。是否有可能默认实现这种行为?
编辑以进一步说明我的问题(我收到了几个可行的解决方案,但我觉得它们都不是完全干净的方法来实现我想要做的事情):
我知道一般的方法是将其保留为空值,这也是我不想在代码中使用空值的原因。我希望保持我的数据传输对象(DTOs)形式如下:
public class ExampleDto
{
public Guid Id { get; set; }
}
请使用以下表单:
public class ExampleDto
{
public Guid? Id { get; set; }
}
为了避免无限的HasValue()检查。然而,我认为更具信息性和一致性的做法是返回这个(参见customerId):
{
"Id": "b3431f4d-ef87-4fb5-83e0-995a9e7c9f6a",
"Name": "A001",
"Description": null,
"Currency": null,
"CustomerId": null,
"Customer": null,
"CountryIso": 2
}
比这更好:
{
"Id": "b3431f4d-ef87-4fb5-83e0-995a9e7c9f6a",
"Name": "A001",
"Description": null,
"Currency": null,
"CustomerId": "00000000-0000-0000-0000-000000000000",
"Customer": null,
"CountryIso": 2
}
这是当前的行为。 这就是为什么我希望让Guid.Empty => null映射由控制器执行而不是AutoMapper(如果可能的话)。