Search code examples
wcfentity-framework-4.1wcf-data-servicesef4-code-only

WCF Data Service and Entity Framework proxy objects


I have a question regarding WCF DataService and Entity Framework 4.1 (code-first). So I have a DataService on web server:

 [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CrmDataService : DataService<CrmDataContext>
    {
        private static CrmDataContext _mdc;
        public static void InitializeService(DataServiceConfiguration config)
        {
            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
            config.UseVerboseErrors = true;
        }

        protected override CrmDataContext CreateDataSource()
        {
            _mdc = new CrmDataContext(@"Data Source=localhost;Database=MyDb;User Id=sqluser;Password=111111;") { TablePrefix = "crm_" };
            _mdc.Configuration.ProxyCreationEnabled = false;
            return _mdc;
        }

I also have a list of entity objects used by my CrmDataContext (such as Company, Address, Person etc.) After adding this service into my client application (into Services namespace e.g.) I got the same entity objects but in the Services namespace. And of course then I want to get any Company object (for example) through Data Service it returns me a set of entity objects from the namespace Services.

So my question is how can I tell data service to use my real entity objects and do not create these other proxy objects in my project? If it is not possible to do, so how can I copy the objects that I get from data service into my real entities?

My goal is to get some entity objects from server through data service using data context and than same them on a client side. I want to use one assembly for all entity objects both in local and server sides.


Solution

  • If you want to use the same objects, then you do not need to add the service into the client application. Just add the assembly containing the types into the referenced assembly, and in the client app, create the DataServiceContext with the service uri.

    You will have to do something like this:

    context.CreateQuery(entitysetName).

    T is the common type that you use across service and client.

    One thing to keep in mind, if the keys in the entity do not follow the convention, you might have to add the DataServiceKeyAttribute or DataServiceEntityAttribute on the type.

    Hope this helps.

    Thanks Pratik