Mixing Fluent API and DataAnnotations in EF code first

不打扰是莪最后的温柔 提交于 2019-11-26 09:59:29

问题


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.

In our experience, it seems that the two configuration styles can be mixed freely, with fluent configuration overriding DataAnnotations. Is this documented anywhere? Is there any risk to doing this mixed configuration?

We are currently using EF 4.3.1


回答1:


I personally haven't ran into any issues with mixing the code first fluent api and data annotations. 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

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




回答2:


You can use Data Annotation attributes and Fluent API at the same time. Entity Framework gives precedence to Fluent API over Data Annotations attributes.




回答3:


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.

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')...

IMO it is 'safer' but only in a way that you can do more and control things exactly as you'd want them. Also helps with keeping things consistent and in one place.



来源:https://stackoverflow.com/questions/15705435/mixing-fluent-api-and-dataannotations-in-ef-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!