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

后端 未结 2 1839
闹比i
闹比i 2020-12-03 05:28

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.

相关标签:
2条回答
  • 2020-12-03 06:08

    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)#>
    
    0 讨论(0)
  • 2020-12-03 06:18

    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
    
    0 讨论(0)
提交回复
热议问题