简体   繁体   English

为什么实体框架实体是部分类?

[英]Why are entity framework entities partial classes?

I recently began using entity framework, and I noticed that generated entities are partial classes. 我最近开始使用实体框架,我注意到生成的实体是部分类。 What are the uses of that? 有什么用途? I googled a bit and people mostly speak of validation, but I can add validation on the generated entity as well. 我google了一下,人们大多说的是验证,但我也可以在生成的实体上添加验证。

For the same reason partial classes typically exist at all, code generation. 出于同样的原因,通常存在partial类,代码生成。

When code is generated; 生成代码时; you don't want your additional methods/properties/whatever blown away, so the designers mark such classes partial to allow users to put additional code in a different file. 你不希望你的其他方法/属性/被吹走,所以设计师将这些类标记为partial允许用户将其他代码放在不同的文件中。

In Code-First, the code-generation aspect of EF has largely become obsolete so any EF model classes you create do not need partial . 在Code-First中,EF的代码生成方面已经基本上已经过时,因此创建的任何EF模型类都不需要partial

partial is added to generated entities for customization. partial被添加到生成的实体中以进行自定义。

In situations when you wish to add your own methods to classes produced by code generators, including EF, it is a good idea to put your implementation in a separate file, so that you wouldn't run the risk of losing your customizations each time the code is re-generated. 在您希望将自己的方法添加到由代码生成器(包括EF)生成的类的情况下,最好将实现放在单独的文件中,这样您就不会冒每次丢失自定义的风险。代码重新生成。

Without partial developers wishing to customize the class would have to use work-around techniques, such as applying Generation Gap design pattern. 如果没有partial开发人员希望自定义类,则必须使用解决方法,例如应用Generation Gap设计模式。

Marking it as partial allows you to put attributes to that class. 将其标记为部分允许您将属性放入该类。
It is handy for example when you need to mark DB generated class as Serializable to be able to store it in Session object (when SQL server mode is used in balanced environments). 例如,当您需要将DB生成的类标记为Serializable以便能够将其存储在Session对象中时(在平衡环境中使用SQL服务器模式时),它非常方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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