none
How do I add DataAnnotations to EF 4.x DbContext Generator generated code? RRS feed

  • Question

  • I have an existing database that I created an edmx file from (Database First). I also generated the model code from the designer using the EF 4.x DbContext Generator. This database will be modified by the DB team during the course of development, meaning that any DataAnnotations added to the generated code will be lost. Are there any examples on how to handle this scenario without losing the DataAnnotation attributes?
    • Edited by Bill2010 Wednesday, June 6, 2012 6:19 PM
    Wednesday, June 6, 2012 6:12 PM

Answers

  • Hi Bill2010,

    Welcome to MSDN Forum.

    If the code is regenerated, we need to add dataannotation by modifying the t4 template manually, please refer to this link. This article introduces how to add dataanotation by modifying t4 template.

    Best Regards


    Allen Li [MSFT]
    MSDN Community Support | Feedback to us

    Friday, June 8, 2012 8:36 AM
    Moderator

All replies

  • Hi Bill2010,

    Welcome to MSDN Forum.

    Do you mean, the DataAnotaions are added after the code generating by DBContext Generator generating? If yes, after generating the code again, we have to add them manually again, because EF doesn't know how we modified the T4 template before. If I understand incorrectly, please feel free to correct me.

    Best Regards


    Allen Li [MSFT]
    MSDN Community Support | Feedback to us

    Thursday, June 7, 2012 6:08 AM
    Moderator
  • Yes. I am using a Database First approach against an existing database that is being developed by the database team and will be changing as the project is refined. From this, I auto-generated the models using the 4.x DBContext template, however there are no dataannotations in this generated code, such as MaxLength, etc. (btw, this would be a nice feature for the code generator if it is possible). But other changes, such as Display, Required, Error message are also necessary. These will be lost when the database changes and the code regenerated.

    I am thinking that buddy classes may be the solution, but this seems a little kludgy.

    Thursday, June 7, 2012 4:30 PM
  • Hi Bill2010,

    Welcome to MSDN Forum.

    If the code is regenerated, we need to add dataannotation by modifying the t4 template manually, please refer to this link. This article introduces how to add dataanotation by modifying t4 template.

    Best Regards


    Allen Li [MSFT]
    MSDN Community Support | Feedback to us

    Friday, June 8, 2012 8:36 AM
    Moderator