简体   繁体   中英

entity framework 4.1 partial class initialisation

在实体Framework 4.1数据库中,首先在生成的c#类中有一个构造函数,那么我在哪里可以进行部分类自定义初始化?

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.

  1. Add a base class:

      public class CallBase { protected CallBase() { Initialize(); } protected abstract void Initialize(); } 
  2. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM