Entity Framework Code First - Advantages and disadvantages of Fluent Api vs Data Annotations [closed]

爱⌒轻易说出口 提交于 2019-11-26 06:14:14

问题


When creating a database using Entity Framework code-first, a lot of the database model is can be extracted from the code. Fluent API and/or Attributes can be used to fine tune the model.

What are the advantages and disadvantages of Fluent Api in comparison to Data Annotations? In other words: Even if in certain situations both methods can be used, in what cases should one method prevail above the other?


回答1:


Everything what you can configure with DataAnnotations is also possible with the Fluent API. The reverse is not true. So, from the viewpoint of configuration options and flexibility the Fluent API is "better".

Configuration examples (for sure not a full list) which are possible in the Fluent API but not with DataAnnotations (as far as I can see):

  • Switch off cascading deletes:

    .WillCascadeOnDelete(false)

  • Specify foreign key column name in the database when the key isn't exposed in your object model:

    .Map(conf => conf.MapKey("MyForeignKeyID"))

  • Fine granular tuning of relationships, especially in all cases where only one side of an association is exposed in the object model:

    .WithMany(...), WithOptional(...), WithRequiredDependent(...), WithRequiredPrincipal(...)

  • Specification of inheritance mapping between object model and database tables (Table-Per-Hierarchy, Table-Per-Type, Table-Per-Concrete-Class):

    .Map<TDerived>(Action<EntityMappingConfiguration<TDerived>> ...)

Edit: Microsoft considers the Fluent API as an "advanced feature" (Quote from here):

The fluent API is considered a more advanced feature and we would recommend using Data Annotations unless your requirements require you to use the fluent API.

But in my opinion you reach the limitations of DataAnnotations very quickly (except perhaps for extremely simple object models). If you cannot fine tune your model with DataAnnotations anymore your last resort is to follow the default mapping conventions (by naming your properties according to those rules). Currently you cannot overwrite the conventions (only disable them; MS announced to give configuration options for the conventions in future EF releases). But if you don't want to be forced by the mapping conventions when you define your object model, your only option then is the Fluent API.

Learning the Fluent API is almost a Must imho, the DataAnnotations are a nice-to-have for simple applications.



来源:https://stackoverflow.com/questions/5354900/entity-framework-code-first-advantages-and-disadvantages-of-fluent-api-vs-data

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