Friday 7 March 2014

Issues faced while passing Entity Framework object directly from WCF

In many n-tier scenarious where data layer (using Entity Framework) and business layer/UI layer are present in seperate services, sending data over the wire can be a bit troublesome.

The main issue here is how to transfer a entity object created by Entity framwork directly from data to business layer over the wire as entity framework objects are specially serialised with atributes for session management. Thats the reason why the names of such objects are also different

eg. <EntityName>_hjxnsioxnasonxi insted of just <entityName>

To bypass this issue we can disable proxy creation in the .context.tt (template) files which are auto generated by Entityframwork and are the architects of your context class.

We can Add the following line to *.context.tt to solve the issue:
base.Configuration.ProxyCreationEnabled = false;

This line can be added at the following location in the .context.tt file

<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{
public <#=code.Escape(container)#>()
    : base("name=<#=container.Name#>")
{
base.Configuration.ProxyCreationEnabled = false;
<#
if (!loader.IsLazyLoadingEnabled(container))

This should solve the problme and you will start getting POCO objects insted of normal entityFramework objects.

The downside of this method is that as the object is converted to POCO objects many features inherently supported by entity framework will be disabled like change tracking and lazy loading.

You can read more about the effects in this post by “Ladislav Mrnka


Workaround source : http://stackoverflow.com/questions/15266435/return-entity-framework-objects-over-wcf

No comments:

Post a Comment