首先在 EF4.1 代码中,使用注释、配置文件或在 OnModelCreating 中配置实体有什么区别?
目前,我使用单独的配置文件并这样调用它们:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ProductConfiguration());
base.OnModelCreating(modelBuilder);
}
看起来大多数在线示例都非常基本,因此它们定义了模型、DbContext 和模型配置,所有这些都在一个类中。是否存在性能问题或其他令人信服的理由来使用其中一种而不是另一种?
Currently I am using separate configuration files and calling them like:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ProductConfiguration());
base.OnModelCreating(modelBuilder);
}
It seems like most of the examples online are really basic so they define their models, the DbContext and the model configurations all in a single class. Are there and performance issues or other compelling reasons to use one over the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道“配置文件”的确切含义,但实际上基本上有三个选项来定义模型:
约定:当您创建模型类时,您以 EF 可以检测主键的方式命名属性、外键、关系等自动。如果您这样做,那么您既不需要任何数据注释,也不需要覆盖
OnModelCreating
。数据注释:当您无法或不想遵循约定规则时很有用。一个示例可能是,您有一个现有数据库,其列名称与 EF 的标准命名规则不匹配,例如,如果您有一个键列,其名称 EF 不会将其识别为键:
Fluent API在
OnModelCreating
中:用于无法使用数据注释定义的高级映射场景。示例如下此处。对于性能,我相信你使用什么并不重要。该方法是一个品味和模型复杂性的问题。 EF 在应用程序实例的生命周期内仅创建一次内部模型表示。 (您可以通过在 OnModelCreating 中设置断点来查看这一点:无论您多久创建一个新的 DbContext,您都只会到达此断点一次。)
I don't know what you mean exactly with "configuration files" but there are indeed basically three options to define a model:
Conventions: When you create your model classes you name your properties in a way that EF can detect primary keys, foreign keys, relationships and so on automatically. If you do this consequently you neither need any data annotations nor to overwrite
OnModelCreating
.Data annotations: Useful when you cannot or don't want to follow the convention rules. An example might be that you have an existing database whose column names doesn't match the standard naming rules of EF, for instance if you have a key column with a name which EF wouldn't recognize as a key:
Fluent API in
OnModelCreating
: For advanced mapping scenarios which you can't define with data annotations. Examples are here.For the performance I believe it doesn't matter what you use. The approach is a question of taste and of the complexity of your model. EF creates an internal model represention only once during the lifetime of an application instance. (You can see this by setting a breakpoint in
OnModelCreating
: You'll reach this breakpoint only once, no matter how often you create a newDbContext
.)不,这只是可读性的问题。随着模型的增长,您可能会在 OnModelCreating 中获得非常大的配置。为了使其更具可读性,您将其分解为单独的配置。
No, it's only a matter of readability. As your model grows you will probably get a very large configuration in OnModelCreating. As to make this more readable you break it up into separate configurations.