How to change T4 POCO Templates of EF 4 for WCF?

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

Thanks to .NET 3.5 SP1 one class does not require to have DataContract attribute to be serializable by WCF. This is fine, but when building real SOA applications, there are always something special you will need. Such special things could be manually changed in POCO templates.
Very good description of using of POCO with EF 4 can be found in ADO.NET team blog.

Because POCO Templates cannot manipulate everything I need related to WCF, I decided to slightly change generated templates. To be able to append Data Contract related attributes, I did following:

 

1. First I added new namespace:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Runtime.Serialization;

 

2. Then I added DataContract attribute on each POCO class:

[DataContract(Namespace="http://daenet.eu")]
<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#><#=code.StringBefore(" : ", code.Escape(entity.BaseType))#>
{
<#
    region.Begin("Primitive Properties");

    foreach (EdmProperty edmProperty in entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity))
    {
        bool isForeignKey = entity.NavigationProperties.Any(np=>np.GetDependentProperties().Contains(edmProperty));
        bool isDefaultValueDefinedInModel = (edmProperty.DefaultValue != null);
        bool generateAutomaticProperty = false;

#>

 

3. Then I added DataMember attributte on each member:

#>
[DataMember(EmitDefaultValue=true)]
    <#=PropertyVirtualModifier(Accessibility.ForProperty(edmProperty))#> <#=code.Escape(edmProperty.TypeUsage)#> <#=code.Escape(edmProperty)#>
    {
<#
        if (isForeignKey)
        {
#>


Note that all changes remains even after EDMX model is changed or updated.


Posted Apr 25 2010, 01:17 PM by Damir Dobric

Comments

Christian Weyer wrote re: How to change T4 POCO Templates of EF 4 for WCF?
on 04-25-2010 15:16

You are talking about "Real SOA"... then why in the first place care about exposing EF4-based entities in the service facade?

Confused...

developers.de is a .Net Community Blog powered by daenet GmbH.