开发者

Why does the Entity Framework generate entities as partial classes?

Other ORMs I've used, such as Torque, Propel or Doctrine, generate 2 classes for each entity: for example, BaseCustomer and Customer. Customer inherits from BaseCustomer, and you can override methods or add your own.

But the Entity Framework generates partial classes. You can add methods, but not override them (constructor or accessor methods).

Why is that?

I guess that its easier for a code generator 开发者_StackOverflowto work with partial classes, and that it prevents developers from messing with the change tracking code, but...

isn't it a disadvantage of the EF, as it restricts developers freedom?


Default code generation for EF is as-is. You cannot modify direct behavior. You can only add your own behavior in partial classes. There is no problem with constructor because as I know EF doesn't create constructor for entities - it uses default one.

In EF 4 this whole changed a lot. You can turn off default entity generator and use T4 template instead. T4 template is just another script file which you can modify and add any changes you need.

If you want better explanation why it is done this way you should ask ADO.NET team but generally partial classes are common way to deal with generated code in whole .NET framework so they probably keep it for consistency.


Inheritance is commonly abused and actually restricts more than partial classes. As a design principal, classes should be open to extension and partial classes do so better than inherited classes.

As for overriding automated entity properties/methods, you can always use the new keyword (if you're using C#):

public MyCustomer : Customerbase {
    public new string FirstName { ... }
}

However, any class inheriting from MyCustomer would default back to the FirstName of Customer.


I can't think of an especially good reason to override a method or property in EF. If you don't want a particular property present and wish to provide your own, don't include it in the entity model. I'll admit that the constructor is a little more of a concern, though you can work around it with a factory method that does what you want.

I suppose all design decisions have tradeoffs -- I have worked with Propel and like its model also, in that context. EF does seem to fit the .NET paradigm well, though, and I have found partial classes "good enough" for extending the entities when I need to do so.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜