In entity Framework 4.1 database first, there is a constructor in the generated c# class, so where can I do my partial class custom initialisation ?
-
I just tried it and the generated classes don't have constructors defined. (I think I'm using EF 4.0.) – svick Aug 21 '11 at 16:11
-
yes it was ok in 4.0, so I was creating my own constructor, but in 4.1 a class with nested types will creates a constructor to init the nested fields – tahir Aug 21 '11 at 16:15
-
1Doesn't the generated constructor call some `partial` method that you could implement? – svick Aug 21 '11 at 16:17
-
no, the class code is very clean (not as in 4.0...) but the class have only the fields, and a constructor, and inherits from nothing, so difficult to customise the initialization – tahir Aug 21 '11 at 16:21
2 Answers
As I understand it, you have a file like Model.edmx in your project that doesn't actually generate any code. Then you have Model.tt, which is what EF 4.1 actually uses to generate the code. And you can modify this Model.tt. So, if you wanted to add a call to partial method OnInitialized()
to each of the generated entities, that is called from their constructors, find the constructor in the code of Model.tt (its first line should look something like public <#=code.Escape(entity)#>()
), add the call to OnInitialized()
somewhere into the constructor and declare the partial method:
partial void OnInitialized();
Regenerate the entities using Run Custom Tool and you're done. You can now do something like this in your non-generated code:
partial class SomeEntity
{
partial void OnInitialized()
{
// custom initialization code goes here
}
}
I don't know EF 4.1, so it's possible that there's a better way.

- 236,525
- 50
- 385
- 514
Add a base class:
public class CallBase { protected CallBase() { Initialize(); } protected abstract void Initialize(); }
Add the partial class implementation in another file
public partial class Call: CallBase { protected owerride void Initialize(); { ... } }
The drawback is that the Initialization method will be called before the all collection creature.

- 3,445
- 1
- 20
- 16