views:

178

answers:

1

I would like some help adding in a POCO .tt Entity Framework template Attributes to support WCF serialization and if its possible how to add namespace usings to each entity.

Thank you.

+2  A: 

You need to open your model1.tt file (or whatever it's called in your project), and add a few things.

Locate these lines of code (line 34, in my case):

// Emit Entity Types
foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
{
    fileManager.StartNewFile(entity.Name + ".cs");

Just before this line here:

<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#><#=code.StringBefore(" : ", code.Escape(entity.BaseType))#>

you need to add the [DataContract] attribute:

[DataContract]
<#=Accessibility.ForType(entity)#> <#=code.SpaceAfter(code.AbstractOption(entity))#>partial class <#=code.Escape(entity)#><#=code.StringBefore(" : ", code.Escape(entity.BaseType))#>

to your template.

Next, locate this line of code:

<#=PropertyVirtualModifier(Accessibility.ForProperty(edmProperty))#> <#=code.Escape(edmProperty.TypeUsage)#> <#=code.Escape(edmProperty)#>

Before that line, add the [DataMember] attribute to your template:

[DataMember]
<#=PropertyVirtualModifier(Accessibility.ForProperty(edmProperty))#> <#=code.Escape(edmProperty.TypeUsage)#> <#=code.Escape(edmProperty)#>

This will add those attributes for all entities and all properties - that might not be what you really want, but it's a start.

Also: to finish off, you probably want to have a look at the WriteHeader function in your T4 template, and add the using System.Runtime.Serialization; statement to your list of usings:

using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Runtime.Serialization;  // add this to handle DataContract/DataMember
marc_s
Thank you, exactly what i need, i think i might start understand T4 minute by minute, i just need some fixes quick right now. Please can you provide some help on where i add using namespaces on each entity?
I have found it, thank you.
@gtas: updated my answer - you'll need to include the extra namespace `System.Runtime.Serialization` to handle the DataContract/DataMember attributes
marc_s