Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF Contracts from Entity Framework?

I've been coming up with a lot of dead ends on this question. Supposedly, .NET 3.5 SP1 has Support for ADO.NET Entity Framework entities in WCF contracts. But when I look for solid info on it I'm not getting a lot of answers. I found this one snippet on an MSDN thread. Does anyone have any experience with this? What happened to the [DataContract]? Is this all there is to it? Why is there so little material on this?

This the answer from Tim Mallalieu in Microsoft.

Entity Types that are generated in the Entity Framework are, by default Data Contracts. If I were to create a simple model in the Entity Designer like the following: The cart Entity Type is by default a DataContract with all properties annotated as data members. We can then use this in a WCF service as follows:

[ServiceContract]

public interface IService1

{
    [OperationContract]
    Cart[] AllCarts();
}



public class Service1 : IService1

{
    public Cart[] AllCarts() 

    {
        using (MSPetShop4Entities context = new MSPetShop4Entities())

        {
            var carts = from c in context.Carts select c;
            return carts.ToArray();
        }
    }
}

As the Entities are DataContracts you can now roll your services as you see fit and send these across the wire.

like image 919
Weej Avatar asked Feb 25 '09 14:02

Weej


2 Answers

I recommend that you not return Entities directly. Unfortunately, Microsoft chose to include implementation-specific data as part of the DataContract for entities. This will not interoperate with other platforms, and is the sort of thing that might fail to interoperate even between .NET versions.

Instead, I recommend you follow the Data Transfer Object pattern and just return POCO classes that are copies of the data in the entities, with no behavior. You can return List of such classes to represent a table, etc.

like image 78
John Saunders Avatar answered Sep 30 '22 19:09

John Saunders


The "sharing interfaces and not type" tenet presupposes that you don't own both ends of the wire and/or you're writing a public-facing web service. WCF can be used (and is used) in contexts where this is decidedly not the case. Many enterprise n-tier architectures have a WCF-fronted application tier to facilitate load-balancing among other things. In these cases it is perfectly valid to share type and, in fact, is desired.

like image 35
Mike Bouck Avatar answered Sep 30 '22 19:09

Mike Bouck