开发者

Using T4 templates to add custom code to EF4 generated entities?

I am getting started with Entity Framework 4, using model-first development. I am building a simple WPF demo app to learn the framework. My app has two entities, Topic and Note. A Topic is a discussion topic; it has Title, Text, and DateRevised properties. Topic also has a Notes collection property. a Note has DateCreated and Text properties.

I have used EF4 to create an EDM and data store for the app. Now I need to add just a bit of intelligence to the entities. For example, the property setter for the Topic.Text property needs to update the Topic.DateRevised property, and a Note needs to set its DateCreated property when it is insta开发者_如何学JAVAntiated--pretty simple stuff. I assume that I can't modify the generated classes directly, because my code would be lost if the entities are re-generated.

Is this the sort of thing that I can implement by modifying the T4 template that EF4 uses to generate the entities? In other words, can a T4 template be modified to add my code for performing these tasks to the entities that it generates? Can you refer me to a good tutorial or explanation of how to get started?

Most of what I have found so far talks about how to add a tt file to an EDM, so I can do that. What I am looking for is a resource that I can use to get to the next level, assuming that a T4 template can be used to customize generated entities as I have described. Thanks for your help.


You can do this without T4, using partial classes and partial methods.

Every EF property will have a partial OnPropertyNameChanged method. If you implement that in a partial class, you can add the behavior you need, and you won't lose your changes when you update.

So you would add a new file, let's say Topic.cs. There, you would write:

namespace MyNamespace
{
    public partial class Topic 
    {
        partial void OnTextChanged()
        {
            this.DateRevised = DateTime.Now;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜