views:

315

answers:

1

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 instantiated--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.

A: 

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;
        }
    }
}
Craig Stuntz
No kidding! Who'd have thought it was that simple? I'm liking EF4 the more I work with it. Any suggestions how to implement the Note.DateCreated code? That would normally go in a constructor, since it is intended to be set only when a Note is created, rather than when its text changes.
David Veeneman
Yes, the constructor is fine. You can add a parameterless constructor to the partial class and it will work. But you might also want to consider your business rules layer, depending upon exactly what you're doing.
Craig Stuntz
For the benefit of anyone else researching this question--I didn't realize that a partial class can have its own constructor. If there are two partial classes, both constructors are run.
David Veeneman