Data Annotations code generation template

Thread is closed for posting
9 posts, 0 answers
  1. 63F75A2C-1F16-4AED-AFE8-B1BBD57646AD
    63F75A2C-1F16-4AED-AFE8-B1BBD57646AD avatar
    1572 posts
    Member since:
    Oct 2004

    Posted 20 Mar 2012 Link to this post

    The following code library applies only to versions  prior to Q2 2013. As of Q2 2013 Telerik OpenAccess ORM supports generation of DataAnnotation attributes out of the box.

    Requirements

    OpenAccess version Q1 2012 SP1 (2012.1.301.2)
    .NET version 4.0
    Visual Studio version 2010
    Programming language C#, VB.Net

    PROJECT DESCRIPTION

    This project demonstrates how to generate data annotation for your domain types based on the domain model schema.
    Data annotations are generated using custom text template that should be included in the domain model project.

    This domain model is based on SofiaCarRental21 sample database.
    SofiaCarRental21 database can be created using the SofiaCarRental21.sql script.

    Data annotation attributes that are supported by this custom code generation template are:
    - KeyAttribute
    - RequiredAttribute
    - StringLenghtAttribute

    In order to achieve the desired result please:
    1. Create a domain model

    2. Add the DataAnnotations.tt template to the project. Set its Custom Tool to "TextTemplatingFileGenerator" if not set.

    3. Edit the template file:
    3.1 Please change line 11:
    For Visual Studio 2010 it should be:
    <#@ Assembly Name="C:\Program Files (x86)\Telerik\OpenAccess ORM\dsl2010\Telerik.OpenAccess.Common.UI.dll" #>

    and for Visual Studio 2012:
    <#@ Assembly Name="C:\Program Files (x86)\Telerik\OpenAccess ORM\dsl2012\Telerik.OpenAccess.Common.UI.dll" #>


    You should replace the value of the assembly name with the full path to Telerik.OpenAccess.Common.UI assembly on YOUR machine.

    3.2 Please change line 13:
    <#@ Assembly Name="C:\Program Files (x86)\Telerik\OpenAccess ORM\bin\Telerik.OpenAccess.dll" #>

    You should replace the value of the assembly name with the full path to Telerik.OpenAccess assembly on YOUR machine.

    3.3 OPTIONAL: Edit the name of the .rlinq file on line 62:
    //return @"[YOUR RLINQ FILE PATH]";

    By default the template will search the directory where it resides for .rlinq files. If it finds one it will use it. 
    You have to change the rlinq file path if:
    - there are more than one domain models in your project
    - the rlinq file discovery routine fails to find your rlinq file for some reason

    4. Transform the DataAnnotations.tt template either by saving it or by invoking the Transform All Templates command in Visual Studio.

    5. Enjoy your auto-generated data annotations.

    If you make any changes in the domain model that affect the data annotation (like addition of new column or change of the allowed string length) you should consider regenerating the data annotation code by invoking Transform All Templates.

    Keep in mind that changes made in the generated code file could easily get lost if the file is regenerated!
    If you need one-time code generation please delete/exclude from project the DataAnnotations.tt in order to prevent any code loss in the generated file.

    If you want to add additional data annotation attributes you can do it in the generated file, but make sure that the text template won't overwrite your changes.
  2. FE9064ED-4C54-421F-BA77-78071934468C
    FE9064ED-4C54-421F-BA77-78071934468C avatar
    12 posts
    Member since:
    Nov 2011

    Posted 04 Oct 2012 Link to this post

    Hi

    I've just used the code generation template and I got to admit it is pretty awesome, saves a lot of time when you got over 15 entities in the diagram. Cheers for the template.

    One query, I've downloaded the .zip file, and ran the template and looked at the data annotations generated. Looking at Employee entity and for the HourlySalary field it generated the following:

           [Required]
           public System.Decimal HourlySalary { get; set; }

    but looking at the entity diagram and looking at the properties for the HourlySalary field it is nullable so why has it put an annotation of [Required]? Surely that shouldn't be there. Looking at the DataAnnotations.tt is it because you calculate isNullable on whether the primative type is nullable? Is it possible to include to check if the property of the field is nullable instead?


    bool isNullable = false;
    MetaPrimitiveType primitiveType = primitiveMember.MemberType as MetaPrimitiveType;
    if(primitiveType != null)
    {
    isNullable = primitiveType.IsNullable;
    }


    Regards Nikesh
  3. 4D47B68D-6843-4480-A8B5-A21D02ADD552
    4D47B68D-6843-4480-A8B5-A21D02ADD552 avatar
    324 posts
    Member since:
    Jul 2017

    Posted 09 Oct 2012 Link to this post

    Hi Nikesh,

    Thank you for your good catch about the redundant use of Required attribute.
    I have updated the T4 templates to add the attribute based on the definition of the underlying database column rather than the nullability of the entity property.

    Please download the updated templates (DataAnnotationSample-CS/VB-v2.zip) and apply them in your project.

    Greetings,
    Viktor Zhivkov
    the Telerik team
    Follow @OpenAccessORM Twitter channel to be the first one to get the latest updates on new releases, tips and tricks and sneak peeks at our product labs!
  4. FE9064ED-4C54-421F-BA77-78071934468C
    FE9064ED-4C54-421F-BA77-78071934468C avatar
    12 posts
    Member since:
    Nov 2011

    Posted 09 Oct 2012 Link to this post

    Thanks Viktor

    I will download and rerun. Will give you feedback on any problems if I find any. Thanks again!
  5. 611D1D6C-D919-440F-A2C0-6DB1CD293DF0
    611D1D6C-D919-440F-A2C0-6DB1CD293DF0 avatar
    14 posts
    Member since:
    Jul 2011

    Posted 08 Apr 2013 Link to this post

    Hi, 

    When i configure and run this .tt , nothing happens. No file gets modified, no error messages are thrown. 
    I can debug the custom tool and see that it runs and goes through all it's methods. 
    Any idea on how to bring this to life? 

    Greets, Tys
  6. 611D1D6C-D919-440F-A2C0-6DB1CD293DF0
    611D1D6C-D919-440F-A2C0-6DB1CD293DF0 avatar
    14 posts
    Member since:
    Jul 2011

    Posted 08 Apr 2013 Link to this post

    Sorry, I thought i had to see some modifications in the original .generated files under my EntitiesModel. But now i see, it creates it's own DataAnnotations.generated.cs! 
    So, thanks anyway, i can continue from here on.
  7. 4D47B68D-6843-4480-A8B5-A21D02ADD552
    4D47B68D-6843-4480-A8B5-A21D02ADD552 avatar
    324 posts
    Member since:
    Jul 2017

    Posted 09 Apr 2013 Link to this post

    Hello Tys,

    I am glad that you were able to resolve the issue.
    You are welcome to share your feedback about the DataAnnotations template or contact us if you have any other questions.

    Greetings,
    Viktor Zhivkov
    the Telerik team
    Telerik OpenAccess ORM Meets ASP.NET Web API. Read more.
  8. 04399E1B-09D6-4BEA-BB3C-373AF81076C3
    04399E1B-09D6-4BEA-BB3C-373AF81076C3 avatar
    1 posts
    Member since:
    Sep 2012

    Posted 13 Oct 2013 Link to this post

    Hi,

    I use the Q2 2013 Sp1. I try to build the simple win form to learn the data annotation.
    I read and download this file also.
    DataAnnotationSample-CS-v2.zip

    I seem work fine. how can I call it from win form app?
    Telerik has generated these clases from my domain model

    Category.generated.cs
    namespace TelerikORMModel   
    {
        public partial class Category
        {
            private int _id;
            public virtual int Id
            {
                get
                {
                    return this._id;
                }
                set
                {
                    this._id = value;
                }
            }
             
            private string _name;
            public virtual string Name
            {
                get
                {
                    return this._name;
                }
                set
                {
                    this._name = value;
                }
            }
             
            private string _notes;
     
            public virtual string Notes
            {
                get
                {
                    return this._notes;
                }
                set
                {
                    this._notes = value;
                }
            }
             
        }
    }


    and

    DataAnnotations.generated.cs

    namespace TelerikORMModel
    {
        [MetadataTypeAttribute(typeof(Category.CategoryMetadata))]
        public partial class Category
        {
            internal sealed class CategoryMetadata
            {
                private CategoryMetadata()
                {
                }           
                 
                [Key]
                [Required]
                public System.Int32 Id { get; set; }
     
                [Required]
                [StringLength(255)]
                public System.String Name { get; set; }
     
               [StringLength(100, MinimumLength = 1, ErrorMessage = " note  1 - 100")]
               [Required(AllowEmptyStrings = false, ErrorMessage = "Notes is required.")]
                public System.String Notes { get; set; }
     
            }
        }
    }


    And I call it from win form:

    private void button1_Click(object sender, EventArgs e)
            {          
                Category c = new Category();
                try
                {
                    c.Id = 11;
                    c.Name = this.textBoxName.Text;
                    c.Notes = this.textBoxNote.Text;
                     
                    ValidationContext context = new ValidationContext(c, null, null);
                    IList<ValidationResult> errors = new List<ValidationResult>();
     
                    if (!Validator.TryValidateObject(c, context, errors, true))
                    {
                        foreach (ValidationResult result in errors)
                            MessageBox.Show(result.ErrorMessage);
                    }
                    else
                        MessageBox.Show("Valid");
     
                }
                catch (ValidationException ex)
                {
                     MessageBox.Show(ex.Message.ToString());
                }
            }


    It does NOT works. whatever the data i entered it's always Valid
    but when i move these 2 lines
               [StringLength(100, MinimumLength = 1, ErrorMessage = " note  1 - 100")]
               [Required(AllowEmptyStrings = false, ErrorMessage = "Notes is required.")]
    to the Category.generated.cs file, it works fine.

    How can I resolve these problem?

    regards.
    Md5
  9. D2394917-F52F-4BE9-A25A-3261F11435D1
    D2394917-F52F-4BE9-A25A-3261F11435D1 avatar
    206 posts
    Member since:
    Sep 2016

    Posted 14 Oct 2013 Link to this post

    Hello,

    The approach described in this article along with the attached sample projects are applicable only for versions of OpenAccess ORM which are older than Q2 2013. As of Q2 2013, OpenAccess supports generation of Data Annotations out of the box - the Data Annotation attributes can be added directly to the generated classes. To see how to do that please refer to this documentation article.

    I hope this helps.

    Regards,
    Kristian Nikolov
    Telerik
    OpenAccess ORM Q3 2013 Beta is available for immediate download in your account. Get it now and play with the latest bits. See what's new >>
Back to Top

This Code Library is part of the product documentation and subject to the respective product license agreement.