Arguably the most important part of Entity Framework is the DbContext. It’s basically a giant object you create with methods to get things out of a database.
Another important aspect of the Application DbContext is that it configures things like the database address, tables, and event advanced relationships for the tables.
In order for any type of data on the internet to be shown. It likely needs a database. Databases needs tables. This is where DbSet<> comes in.
DbSet in EF Core
DbSet essentially takes the model you pass into the alligator clips (<Stock>) and signals to EF Core that this is going to be a database table. Database tables are nothing more then fancy excel spreadsheets that can be linked together via foreign keys.
But wait…. this is where things get interesting.
This also creates an object for the table that you can manipulate throughout the entire app! The power at your finger tips is unimaginable and you have no idea…. yet.
With simple LINQ commands you can chain .filter(), .select(), etc to quickly manipulate data out of your fancy excel spreadsheet in ways most could never comprehend!
onModelCreating in EF Core
I’m a Java dev and even onModelCreating makes me looks at this code and think “wtf is this shit?”. It took me a while to understand!
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<AppUserStock>().HasKey(i => new { i.StockId, i.AppUserId });
}
OnModelCreating is very powerful. It will likely be your lifeline in professional environments where you will have layers of complex database relationships.
%100 Guarantee: One day you will work on a database so complex that you slowly begin to realize nobody knows whats going because the database is so fucked up.
In a nutshell, we are using the builder pattern to chain methods on our onModelCreating. The actual builder object is going to be passed in upon creation of your database and do configurations for you based on how you chain methods on the “builder”.