locked
Data Annotations in T4 templates RRS feed

  • Question

  • Hi,

    I am writing a Silverlight application using EF4, T4 templates and RIA services. My domain service requires my entities to use the 'System.ComponentModel.DataAnnotations' to decorate my properties with the [Key] tag for the primary keys. I've been able to modify the T4 template to include 'using System.ComponentModel.DataAnnotations;' in my entities but this was fairly straight forward. What I can't work out (and an extensive search of Google has not helped) is how to identify primaries keys in the T4 and add the [Key] decoration?

    I'm using the ADO.NET C# POCO Entity Generator (http://visualstudiogallery.msdn.microsoft.com/23df0450-5677-4926-96cc-173d02752313).

    Any help would be greatly appreciated.

    Cheers

    Stephen 

     


    Stephen
    Tuesday, April 19, 2011 12:16 PM

Answers

  • I've worked this one out myself. See below:

    // SDC 19th April 2011
    // Identify a primary key 
    bool isPrimaryKey = ef.IsKey(edmProperty);
    #>
    
    <#
    if (isPrimaryKey)
      {
    #>
      [Key]
    <#
      }
    #>
    <#=PropertyVirtualModifier(Accessibility.ForProperty(edmProperty))#> <#=code.Escape(edmProperty.TypeUsage)#> <#=code.Escape(edmProperty)#>
    
    

    Stephen
    • Marked as answer by -Ozymandias- Tuesday, April 19, 2011 2:00 PM
    Tuesday, April 19, 2011 2:00 PM

All replies

  • I've worked this one out myself. See below:

    // SDC 19th April 2011
    // Identify a primary key 
    bool isPrimaryKey = ef.IsKey(edmProperty);
    #>
    
    <#
    if (isPrimaryKey)
      {
    #>
      [Key]
    <#
      }
    #>
    <#=PropertyVirtualModifier(Accessibility.ForProperty(edmProperty))#> <#=code.Escape(edmProperty.TypeUsage)#> <#=code.Escape(edmProperty)#>
    
    

    Stephen
    • Marked as answer by -Ozymandias- Tuesday, April 19, 2011 2:00 PM
    Tuesday, April 19, 2011 2:00 PM
  • Hi a2Ton,

    Thanks for sharing your experience here! 

    It will be very beneficial for other community members having the similar questions.

    Have a nice day.


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, April 20, 2011 2:13 AM
  • Thanks. It's 3 years later but you helped me out!

    rvenable

    Wednesday, April 23, 2014 5:03 PM