DTOs vs Serializing Persisted Entities

2019-01-14 19:34发布

I'm curious to know what the community feels on this subject. I've recently come into the question with a NHibernate/WCF scenario(entities persisted at the service layer) and realized I may be going the wrong direction here.

My question is plainly, when using a persistent object graph(NHibernate, LINQ to SQL, etc) behind a web service(WCF in this scenario), do you prefer to send those entities over the wire? Or would you create a set of lighter DTO's(sans cyclic references) across?

5条回答
孤傲高冷的网名
2楼-- · 2019-01-14 19:45

I've almost always created dtos to transfer over the wire and use richter entities on my server and client. On the client they'll have some common presentation logic while on the server they'll have business logic. Mapping between the dtos and the entities can be dumb but it needs to happen. Tools like AutoMapper help you.

查看更多
冷血范
3楼-- · 2019-01-14 19:46

I've always had problems sending nHibernate objects over the wire. Particularly if your using a ActiveRecord model. and/or if your object has ties to the session (yuck). Another nasty result is that nHibernate may try and load the object at the entry of the method (before you can get to it) which can also possibly cause problems.

So...getting the message here? problems, problems problems...DTO's all the way

查看更多
孤傲高冷的网名
4楼-- · 2019-01-14 19:49

DTOs. Use AutoMapper for object-to-object mapping

查看更多
地球回转人心会变
5楼-- · 2019-01-14 19:51

If you're asking do I send serialized entities from a web service to the outside world? then the answer is definitely no, you're going to get minimal interoperability if you do that. DTOs help solve this problem by defining a set of 'objects' that can be instantiated in any language whether you're using C#, Java, Javascript or anything else.

查看更多
三岁会撩人
6楼-- · 2019-01-14 19:52

I've been in this scenario multiple times before and can speak from experience on both sides. Originally I was just serializing my entities and sending them as is. This worked fine from a functional standpoint but the more I looked into it the more I realized that I was sending more data than I needed to and I was losing the ability to vary the implementation on either side. In subsequent service applications I've taken to created DTOs whose only purpose is to get data to and from the web service.

Outside of any interop, having to think about all the fields that are being sent over the wire is very helpful (to me) to make sure I'm not sending data that isn't needed or worse, should not get down to the client.

As others have mentioned, AutoMapper is a great tool for entity to DTO mapping.

查看更多
登录 后发表回答