Data Annotations Vs Fluent API

Hi new to the forum

And I’m watching the Entity Framework Lecture

I understand Mosh’s concerned with the magic string in the Data annotations but a solution could be to Specify it like this

public int AuthorId { get; set; }
public virtual Author Author { get; set; }

That way if the base Class name Changes the Annotation changes with it

My main Concern with the Fluent API approach is that the Model and the Database table is Disconnected.

The benefit of Entity framework in my opinion is that the Models and the Database object are hard cupped.

I don’t see the benefit of the Fluent API approach, other than obfuscating The code for new Programmers on the Project.

Are the concerns i have valid? or are there reasons to use Fluent API over Annotations ?


When I was trained .NET we only saw the annotation approach.
When I took Mosh’s EF course I learnt more about fluent API (I met a bit of it here and there without knowing much).
I personnaly prefer Fluent API because it allows cleaner code IMHO.
You can have a full description of your code in one place (actually that one place is a folder with as many configuration files as needed and OnModelCreating() calling them)

I am working on a migration from an old project to .NET 6 and it has a bit of both approaches (Because legacy code has annotations yet they scaffolded the model from DB which produces Fluent API).
Ultimately they should go with the fluent API approach.

Just like many things in our field there are different preferences for different reasons.
The same project in the same situation but different lead devs could go different ways.

Just have your own preference and adapt anyway.