Up to now, when working with WCF, I have always been exposing the whole either EF generated entities, or POCOs(by modifying the T4 template to include DataContract and DataMember on POCOs and properties) as DataContract.
Now, I have come across a situation that I cannot expose the whole thing, and need to explicitly specify my DataContract to be a subset of the entities.
It worth saying that one of my entities is something like below:
And I want to just expose Id, Name, CategoryId, Price.
Insert/Update of rest of the fields (ActiveFrom
, InactiveDate
, Supported
) is something that will be decided based on the BR, and client doesn’t know , and should not know indeed, anything about them.
I have tried following approaches, but each of them seems to have problem/not working:
Using AutoMapper : I need to map a source object to a destination object, and this is a one way mapping, so for presentation purposes I can map
Product
toProductContract
. But for adding/updating the product, it does not work as it cannot do a two way mapping.Use the reflection and create a metadata class for the entities and add the
[DataMember]
attribute to the properties of the Metadata class as below (please note that I haven’t included the unwanted fields):public class ProductMD : AssociatedMetadataTypeTypeDescriptionProvider { public ProductMD() : base(typeof(Product)) { } [DataMember] public int Id{ get; set; } [DataMember] public string Name { get; set; } [DataMember] public int? CategoryID { get; set; } [DataMember] public decimal? Price { get; set; } }
And then use the
ProductMD
as an attribute for theProduct
partial class without touching the auto-generated entity (FYI: I have changed the POCO T4 template generator to include the[DataContract]
on each entity):[MetadataType(typeof(ProductMD))] public partial class Product { }
But on the client side, I do not have access to any of the
DataMembers
of the Product.
Now my question is that, what is the best approach to gain what I want to do (exposing a subset of the entities as DataContract
)?