EF Core “Underneath The Hood”

Getting up and running with EF Core is easy, but it often pays dividends to understand how underlying technologies work. My aim is to provide a solid mental model of what’s going on when you actual access the database.

Modeling

When we first start programming, rarely do we ever start with a database.

We must create our database from scratch! This is where modeling comes in. The term “modeling” is very indicative of what is going on.

Modeling is a fancy way of saying “EF Core is going to take my code and try to make a database”.

FUN FACT: The opposite is true when you work for an employer. A test/dev database will be given to you that “simulates” a real environment. i.e “database first”.

  1. First, EF Core will look at all classes you have specified in the Application DbContext
  2. It will find all references to other tables.
  3. Lastly, it runs OnModelCreating which will override any other settings you have.

While technically not apart of this process, an internal model is stored and cached for faster access.

Read

If you haven’t given up yet (LOL), congratulations you can now read data!

Reading data is arguably the most important part of software because people need to read software on screens.

EF Core uses LINQ to carry commands and THANK GOD!

FUN FACT: We all drank the OOP punch. But never use for loops in production code. Stay functional, my friends!

This code is simply finding ANY stock.

But what is REALLY going on? It simply takes “what we want” and generates SQL.

It isn’t technically accessing the database…. yet. Why? Because it is being cached.

Hitting the database with a HUGE query isn’t the best idea so cache and wait till the query is optimized…

Once the code “reaches” .AnyAsync(), that is when SQL actually hits database and magic happens.

Our database creation has just given birth to beautiful object babies. Oh boy lol.

Updating

Let’s just say we are raging TSLA bears and want to change our stock to PLTR because I currently have a few grand it (fact).

var singleStock = db.Stocks.Single(stock => stock.Ticker == "TSLA");
singleStock.Ticker = "PLTR"
db.SaveChanges();

This code looks very simple, but is actually very complex underneath.

Updating is an entirely different beast compared to reads.

singleStock.Ticker = "PLTR"

The most complex part of the code is actually the code above, because of TRACKING.

EF Core is quietly checking your code for equality. When equality has been compromised it knows, but doesn’t execute the query till….

db.SaveChanges()

Once SaveChanges() is run if EF Core senses change, it will generate the SQL and send to the database.

Posted in C#

Leave a Reply

Your email address will not be published. Required fields are marked *