Entity framework, related records and dynamic proxy

Most of the times a database consist of related records. If you have used entity framework you have defined your poco classes and in these poco classes you have defined your relations. something like this:

    public class Klant 
        public string Id { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }

        public virtual ICollection Projecten { get; set; }

This just means that the entity framework is going to create a relationship with the Project table based on the KlantId.

Now if you want to use this object with a WebService, for instance a WCF Rest service you will receive a serializing error. The Klant object cannot be serialized because the entity framework creates a dynamic proxy for the Projecten collection

The dynamic proxy is used by the entity framework to keep track of changes in the Projection collection. But because a Rest service is stateless this dynamic proxy isn't neccessarely and can be turned off. After turnng off the dynamic proxy you will see that it's serializable again and your webservice is returning the object in Json

Turn of dynamic proxy:

        public IEnumerable SelectAllIncludeProjects()
            // disable proxy
            database.Configuration.ProxyCreationEnabled = false;
            // query 
            var foundResult = dbset.Include("Projecten").ToList();
            // enable proxy
            database.Configuration.ProxyCreationEnabled = true;

            return foundResult;

Because of default lazy loading principle of the entity framework you will have to include  the projecten. You can make this default by turning of lazy loading




Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!