开发者

Is it possible to use entities as data contracts?

Is it possible to use objects of Entity classes as Data Contract on WCF service ? So I can send them on the client side. is this good design approach ?

I want to my entity classes to be used as DTOs too, so I can send the data retrieved from database to 开发者_StackOverflow社区the client.


Yes it is. If you use EntityObject based entities both default code generator and T4 template should mark them with DataContract and DataMember attributes. If you use POCOs you will have to either modify template to generate these attributes for you or create POCOs manually.

The reason why you need to use those attributes is problem with circular reference. By default EF creates navigation properties on both sides of relation. During serialization, framework needs some hint to know about that circular reference otherwise it will go to infinite loop. To avoid that the entity must be marked with [DataContract(IsReference=true)] and once you use DataContract attribute you must use DataMember to mark each serialized property.

It is also important to turn off lazy loading because otherwise serialization will trigger lazy loading on every navigation property and it will do this recursively on all lazily loaded entities. So instead of single object you can return from your service all its relations, all their relations, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜