Adding [DataMember] [DataContract] attributes in Entity Framework POCO Template

17,945

Solution 1

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

Solution 2

In EF6.1 you need to edit the model1.tt and add tag between UsingDirectives and EntityClassOpening:

<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
//MY TAG:
[Serializable]
<#=codeStringGenerator.EntityClassOpening(entity)#>
Share:
17,945
George Taskos
Author by

George Taskos

Updated on June 03, 2022

Comments

  • George Taskos
    George Taskos almost 2 years

    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.