1 回答
TA贡献1834条经验 获得超8个赞
我将假设您使用的是 Web Api,但同样的原则也适用于 MVC 应用程序。我通常有一个映射器层,它接受一个域对象并将其映射到视图模型或 dto。这样,您可以在任何时候想要返回相同的视图模型时重用映射器。因此,如果您对视图模型进行更改,它都位于一个地方。
请参阅下面的代码以回答问题 1。
问题 2:为什么您的 mircoservice 关心客户想要的日期。如果您发回 utc 日期,那么如果客户想要它的格式,那么由他们来格式化。
//Fake view model
public class CalendarEventViewModel
{
public int EventId { get; set; }
public string Title { get; set; }
public DateTime? StartDateTimeUtc { get; set; }
public DateTime? EndDateTimeUtc { get; set; }
public string Summary { get; set; }
public bool IsApproved { get; set; }
public string TimeZoneId { get; set; }
}
public interface IMapper<in TIn, out TOut>
{
TOut Map(TIn model);
}
public class CalendarEventViewModelMapper : IMapper<CalendarEvent, CalendarEventViewModel>
{
public CalendarEventViewModel Map(CalendarEvent model)
{
return new CalendarEventViewModel
{
EndDateTimeUtc = model.EndDateTimeUtc,
EventId = model.EventId,
IsApproved = model.IsApproved,
StartDateTimeUtc = model.StartDateTimeUtc,
Summary = model.Summary,
TimeZoneId = model.TimeZoneId,
Title = model.Title
};
}
}
[Route("api/Values")]
public class ValuesController
{
public ValuesController( IMapper<CalendarEvent, CalendarEventViewModel> calendarMapper)
{
_calendarMapper = calendarMapper;
}
// GET api/values/5
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var calendarEvent = GetMyCalendarEventFromDB(id);
return this.Ok(_calendarMapper.Map(calendarEvent));
}
private CalendarEvent GetMyCalendarEventFromDB(int id)
{
return new CalendarEvent("yyyy-dd-MM")
{
EndDateTimeUtc = DateTime.UtcNow.AddHours(3),
EventId = id,
IsApproved = true,
StartDateTimeUtc = DateTime.UtcNow.AddHours(2),
Summary = "My magical Event",
TimeZoneId = "UTC",
Title = "Magical Event"
};
}
}
}
- 1 回答
- 0 关注
- 131 浏览
添加回答
举报