Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

entity framework 4.1 partial class initialisation

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 ?

like image 273
tahir Avatar asked Sep 15 '25 18:09

tahir


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

like image 184
svick Avatar answered Sep 18 '25 10:09

svick