Adding code to Entity Framework 4 generated POCOs

江枫思渺然 提交于 2020-01-05 07:07:28

问题


Starting from an EF 4 entity diagram and using T4 templates one can create POCO classes that can be used inside the Domain Model. The generated code looks like this:

public partial class Product
{
    public virtual int Id
    {
        get;
        set;
    }

    public virtual string Name
    {
        get;
        set;
    }
   //and so on
}

Is there any elegant approach to add my own code for implementing the properties? for example, the Name setter I would like to be implemented by lowering all the characters. I would like that my code resist to repeated regeneration of the POCO classes from the EF diagram.

This requirement is somewhat similar to adding validation code to the POCO classes. This issue is already solved by creating a separate validation class and linking it to the POCO through the MetadataType attribute. That separate validation class is not overwritten by repeatedly regenerating POCOs from the EF diagram.

Thanks,

Lucian


回答1:


No there is no easy way to do that. You must not touch generated code because your changes will be deleted after each regeneration. You options are:

  • Write entities yourselves and don't use generator - you will get full control over entity code
  • Modify T4 template in generator to either add your direct code (this can be quite hard to generalize) or simply add call to partial methods (you must also declare these methods in generator) in getter and setter and in your partial part of entity class implement partial methods you need.


来源:https://stackoverflow.com/questions/8475469/adding-code-to-entity-framework-4-generated-pocos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!