通过 WCF 公开实体
我有一个使用 ADO.NET 实体数据模型来访问 SQL Server 的 WCF。
要在具有七列的表中插入新行,我使用 WCF 方法。
我认为发送七个参数太多了,所以我可以使用结构体或表的实体对象。
你怎么认为?您建议我通过 WCF 公开实体对象吗?或者我需要使用一个结构来避免这样做。
I have a WCF that uses a ADO.NET Entity Data Model to access SQL Server.
To insert a new row in a table with seven columns I'm using a WCF method.
I think send seven parameters it's too much, so I can use a struct or table's entity object.
What do you think? Do you recommend me to expose an entity object through WCF? Or I need to use a struct to avoid do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于您的应用程序的大小/复杂性。公开实体是可能的,但在传输整个对象图(实体及其关系)时可能会导致一些序列化问题。这些问题通常通过使用
DataContract
和DataMember
属性标记实体来解决(如果您使用 EFv1 或在 EFv4 中使用默认实体生成 = 无 T4 模板,则默认使用)。如果您想遵循干净的架构和良好的关注点分离,建议使用您描述的第二种方法,但它会使您的应用程序更加复杂(另一层对象、转换等)。为数据传输而创建的结构或类通常称为 DTO(数据传输对象)。
数据传输对象允许您仅传输实体所需的必要数据子集。例如,如果您在实体中有一些基础结构属性(如 CreatedAt、CreatedBy),您将不希望客户端设置这些属性,因为设置它们是服务的责任。因此,不需要允许客户端传递它们。通过不在 DTO 中公开这些属性,您可以清楚地表明这一点。
It depends on size / complexity of your application. Exposing entity is possible but it can cause some serialization problems when transporting whole object graph (entity with its relation). These problems are usually solved by marking entities with
DataContract
andDataMember
attributes (used by default if you use EFv1 or default entity generation in EFv4 = no T4 templates).The second approach you described is recommended if you want to follow clean architecture and good separation of concerns but it will make your application more complex (another layer of objects, conversions, etc.). Structures or classes created for data transportation are generally called DTOs (Data Transfer Objects).
Data Transfer Objects allow you transferring only necessary subset of data required for entity. If you for example have some infrastructural properties in the entity (like CreatedAt, CreatedBy) you will not want client to set these properties because it is responsibility of the service to set them. Because of that there is no need to allow client passing them. By not exposing these properties in the DTO you will make this clear.
我使用实体作为数据契约的经验是,您会不断遇到各种麻烦。维护 DTO 并不理想,但可以为您提供非常细粒度的控制,包括在不更改合同的情况下更改数据库架构的能力,以及对服务公开的字段的控制。
Automapper 确实可以帮助您:http://automapper.codeplex.com/
My experience of using entities as Data Contracts is that you continually run into all kinds of hassle. Maintaining DTOs is not ideal, but gives you very fine grained control including the ability to change your DB schema without changing your contracts, and also control over the fields exposed by your service.
Automapper can really help you: http://automapper.codeplex.com/