Entity Framework Code First 是否允许在单独的文件中进行流畅的映射?
我正在使用实体框架代码优先开发一个相当大的数据库模式。与数据注释方法相比,我更喜欢 Fluent API,因为它将我的域对象保留为简单的 POCO。
为了使用 Fluent API,我必须在继承自 DbContext 的类中重写 OnModelCreating。
我不喜欢我的所有实体的所有映射都在这一种方法中。我以前使用过像 FluentNHibernate 这样的东西,其中每个实体都有它自己的映射类。 EF有类似的吗?
我想我可以创建自己的接口来实现映射类并在 OnModelCreating 方法中调用它们。我可以使用反射或 IoC 来发现它们。我没有特别看到这种方法有什么问题,但我想知道实体框架是否已经提供了这样的开箱即用的东西?
I am developing a rather large database schema using Entity Framework Code First. I prefer the Fluent API over the Data Annotations approach, as it leaves my domain objects as simple POCOs.
In order to use Fluent API, I have to override OnModelCreating in the class that inherits from DbContext.
I don't like that all mappings for all of my entities are in this one method. I have used things like FluentNHibernate before, where each entity has it's own mapping class. Does EF have anything similar?
I suppose I could create my own interface to implement a mapping class and call them all within the OnModelCreating method. I could use reflection or an IoC to discover them all. I don't particularly see anything wrong with this approach, but I was wondering if Entity Framework already comes with something like this out of the box?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以为从
EntityTypeConfiguration
派生的每个实体创建一个配置类,并将这些类放入单独的文件中。在派生的 DbContext 中,您可以将这些配置类的实例添加到模型构建器中。示例:派生上下文:
您还可以派生一个
ComplexTypeConfiguration
来配置复杂类型。You can create one configuration class per entity derived from
EntityTypeConfiguration<TEntity>
and put these classes into separate files. In your derivedDbContext
you add instances of those configuration classes to the model builder. Example:Derived context:
There is also a
ComplexTypeConfiguration<T>
you can derive from to configure complex types.