Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does .NET Core Entity Framework Create Tables From Model

I'm new to .NET Core, and I am exploring this particular tutorial: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-2.2&tabs=visual-studio

Now it seems the Entity Framework takes a code first approach to generate the database tables from the created model, and the tutorial uses this scaffolding thing to create the views and controller before generating the tables via the package manager console.

My question is: I was wondering how does the solution really know which models are to be pushed to the database on Update-Database? I have added some standalone model DBSets to the DBContext manually (in the tutorial MvcMovieContext), but that didn't seem to work. Is it the Migrations folder? How does it work?

I would think that this scaffolding step isn't necessary (especially if I would like to maintain the tables without any UI interfaces), and that it has some kind of list somewhere that says which model object goes into database or not.

like image 927
aykl104001 Avatar asked Jan 28 '26 10:01

aykl104001


1 Answers

Entity Framework (Core) works the following: By creating a DbContext or any class that derives from it, EF Core checks for DbSets and their related classes in the code. Take for example this DbContext:

public class StackOverflowDbContext : DbContext {
    public DbSet<MyClass> Test { get; set; }
}

As soon as you start with your initial migration (can be done for example via dotnet ef migrations add Initial), EF checks for a DbContext class. If there are multiple, you need to specify that, otherwise it takes the first available and analyses it. In this case, the MyClass needs to be added to the database and therefore the class and all it's properties start to appear in the initial migration.

From there, you can update your model whenever you want, but do not forget to create a new migration after that.

I would think that this scaffolding step isn't necessary

And yes, that is true. You don't need to use scaffolding, it's just there for providing a starting point.

like image 166
nachtjasmin Avatar answered Jan 30 '26 22:01

nachtjasmin