WCF, Entity Framework & Data Contracts

喜欢而已 提交于 2019-11-29 02:23:24

Are you aware that your entities do not need to map one to one with the database? In particular, you can leave out columns, or even entire tables that are not relevant.

The entity model is meant to be a conceptual model. You can easily create a set of entities for exposure to one set of clients (web services, perhaps), and another set, mapping to the same database, that is meant for a different client (web application, perhaps).

On the other hand, I always recommend against ever exposing Entity Framework objects through a web service. Microsoft unfortunately exposes implementation-dependent properties by marking them with [DataMember]. I just now tried this with a simple service returning a SalesOrderHeader from AdventureWorks. My client received proxy versions of the following EF types:

  • EntityKeyMember
  • StructuralObject
  • EntityObject
  • EntityKey
  • EntityReference
  • RelatedEnd

These are not things your clients need to know about.

I prefer exposing Data Transfer Objects, and copying the properties from one to the other. Obviously, this is better done through reflection or code generation, than by hand. I've done it through code generation in the past (T4 templates).

An option I haven't tried is AutoMapper.

We use separate classes for the DataContract objects. We have an interface with one method, ToContract(), and all of our entities implement this interface in a partial class file. It's extra work, and it's boilerplate, but it seems the simplest way to get the separation and granularity of control we need.

I basically see two things you can do:

  1. Either you remove those items you don't want to expose from the DataContract by manually removing the [DataMember] attribute on those items; in that case, WCF will not serialize the properties out
  2. You define your own WCF DataContract classes with just those members you want, and you come up with a logic to convert from your EF entities to your WCF DataContract, using e.g. something like AutoMapper to eliminate (or at least limit) the tedious assigment operations between EF and WCF entities.

Marc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!