简体   繁体   English

首先在 EF 代码中混合 Fluent API 和 DataAnnotations

[英]Mixing Fluent API and DataAnnotations in EF code first

While we mostly use fluent configuration for our code-first POCOs, we have found it useful to use data annotations for things like the table name, PKs, etc. since it makes it easier for non-EF components that don't have a reference to the ObjectContext to interact with these entities.虽然我们主要为代码优先的 POCO 使用流畅的配置,但我们发现对表名、PK 等使用数据注释很有用,因为它使没有引用的非 EF 组件更容易到 ObjectContext 与这些实体进行交互。

In our experience, it seems that the two configuration styles can be mixed freely, with fluent configuration overriding DataAnnotations.根据我们的经验,这两种配置风格似乎可以自由混合,流畅的配置覆盖DataAnnotations。 Is this documented anywhere?这在任何地方都有记录吗? Is there any risk to doing this mixed configuration?进行这种混合配置有什么风险吗?

We are currently using EF 4.3.1我们目前使用的是 EF 4.3.1

You can use Data Annotation attributes and Fluent API at the same time.您可以同时使用 Data Annotation 属性和 Fluent API。 Entity Framework gives precedence to Fluent API over Data Annotations attributes.实体框架优先于 Fluent API 而非数据注释属性。

I personally haven't ran into any issues with mixing the code first fluent api and data annotations.我个人在将代码优先的 fluent api 和数据注释混合时没有遇到任何问题。 I also wondered if there would be any crossover pain and I can honestly say I have yet to find any.我还想知道是否会有任何交叉疼痛,老实说我还没有找到。 Here's a few references to case studies on the subject to ease your mind.这里有一些关于该主题的案例研究的参考资料,以减轻您的负担。

(Direct from the EF team) http://msdn.microsoft.com/en-us/data/jj591583.aspx (直接来自 EF 团队) http://msdn.microsoft.com/en-us/data/jj591583.aspx

(Part 1) http://www.codeproject.com/Articles/476966/FluentplusAPIplusvsplusDataplusAnnotations-plusWor (第 1 部分) http://www.codeproject.com/Articles/476966/FluentplusAPIplusvsplusDataplusAnnotations-plusWor

I don't think it's a risk - as both things have equivalent counterparts for the most of it.我不认为这是一种风险——因为在大多数情况下,这两种东西都有相同的对应物。

But, personally, when I run into some sort of issues around structuring my entities - first thing I do is to remove annotations if any - and move all to fluent.但是,就我个人而言,当我在构建实体时遇到某种问题时 - 我做的第一件事就是删除注释(如果有的话) - 并将所有内容移到 fluent。

Which over time led me to use pretty much straight fluent configuration (also freeing my my objects of any ties with the Db 'state of mind')...随着时间的推移,这让我使用了非常直接的流畅配置(也让我的对象摆脱了与 Db“心态”的任何联系)......

IMO it is 'safer' but only in a way that you can do more and control things exactly as you'd want them. IMO 它“更安全”,但只有这样,您才能做更多事情并完全按照您的意愿控制事情。 Also helps with keeping things consistent and in one place.还有助于使事情保持一致并集中在一个地方。

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

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