我觉得我已经通过使用 DTO 使我的设计过于复杂,但我正在寻找第二个意见。
我的结构是:
- 用户 <- 一对多 -> 播放列表 <- 一对多 -> 播放列表项 <- 一对一 -> 视频
因此,PlaylistItem 域对象如下所示:
public class PlaylistItem
{
public virtual Guid Id { get; set; }
public virtual Playlist Playlist { get; set; }
public virtual int Sequence { get; set; }
public virtual string Title { get; set; }
public virtual Video Video { get; set; }
// Not written to the database. Used for client to tell who is who after a save.
public virtual string Cid { get; set; }
}
PlaylistItem DTO 看起来像:
[DataContract]
public class PlaylistItemDto
{
[DataMember(Name = "playlistId")]
public Guid PlaylistId { get; set; }
[DataMember(Name = "id")]
public Guid Id { get; set; }
[DataMember(Name = "sequence")]
public int Sequence { get; set; }
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "video")]
public VideoDto Video { get; set; }
[DataMember(Name = "cid")]
public string Cid { get; set; }
}
唯一的变化是我通过用 PlaylistId 替换播放列表引用打破了循环引用结构。
C# .NET MVC 中的默认 JSON 序列化程序无法处理循环结构。我已经更新为使用能够处理循环结构的 JSON.NET 序列化程序。我现在正在重新评估为什么我什至需要我的 DTO。
我应该在此处了解/考虑 DTO 的任何好处吗?将循环引用 JSONize 化并通过网络发送它是一种不好的做法吗?
请您参考如下方法:
JSON 作为一种分层格式,在以分层方式表示数据时效果最佳。 JSON 不是节点图,因此我认为尝试序列化类似图的数据将被证明是困难的。我认为您将对象 (Playlist) 转换为一种“引用”形式 (PlaylistId) 的解决方案是正确的。接收和处理此 JSON 的代码可以在必要时重建循环引用,因为您已经有了“外键”(PlaylistId)。
大多数时候,我宁愿有一个额外的 DTO,也不愿一个也没有。 DTO 使您免受变化的影响——在本例中,使您的 API 免受变化的影响。 PlaylistId 将来不太可能更改其架构,但实际的 Playlist 可能会更改。
