Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 905
ChaseMedallion Avatar asked Mar 29 '13 14:03

ChaseMedallion


People also ask

Does data annotation attributes override Fluent API configuration?

To write Fluent API configurations, override the OnModelCreating() method of DbContext in a context class, as shown below. You can use Data Annotation attributes and Fluent API at the same time. Entity Framework gives precedence to Fluent API over Data Annotations attributes.

Should I use Fluent API or data annotations?

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.

Does EF core support Fluent API?

Entity Framework Fluent API is used to configure domain classes to override conventions. EF Fluent API is based on a Fluent API design pattern (a.k.a Fluent Interface) where the result is formulated by method chaining. In Entity Framework Core, the ModelBuilder class acts as a Fluent API.

How do you set composite primary key in Fluent API?

The only way to configure composite keys is to use the HasKey method. You specify the properties that form the composite key by passing them in as properties of an anonymous type to the HasKey method.


1 Answers

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

like image 92
e03050 Avatar answered Sep 29 '22 07:09

e03050