In this post, we are going to look at how to approach the code first methodology in Entity Framework Core. For those of you unfamiliar with Entity Framework, it is a Microsoft framework that makes creating database applications easier, as we saw in one of the previous posts.
Index
1 - What is Code first in Entity Framework Core?
The code first approach in Entity Framework Core means that you design and code your data model classes, and then Entity Framework Core creates the database, or the corresponding tables, from those classes.
For this post, we will use the same structure we saw in the previous post about database first. Also, don't forget that all the code is available on GitHub.
2 - Implementing code First with Entity Framework Core
The first thing we need to do is create a class for each table in our database.
In this case, we create the two entities we need:
public class User{ public int Id { get; set; } public string UserName { get; set; } }public class Wokringexperience{ public int Id { get; set; } public int UserId { get; set; } [MaxLength(50)] public string Name { get; set; } public string Details { get; set; } public string Environment { get; set; } public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; }}
As you can see, you can include annotations in the properties, in this case a 50 character limit in the database column name.
Now, before moving on, we install Microsoft.EntityFrameworkCore.Design
and the MySQL package because my database is MySQL. If you use SqlServer or another provider, this second package will be different.
Next, we create the class that inherits from DbContext
and defines the instance of the database, as well as the tables it contains.
public class CursoEfContext : DbContext{ public virtual DbSet<User> Users { get; set; } public virtual DbSet<Wokringexperience> Wokringexperiences { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263. => optionsBuilder.UseMySQL("server=127.0.0.1;port=4306;database=cursoEF;user=root;password=cursoEFpass");}
As you can see, in the DbContext we have configured both the tables and the connection to the database, although this part can be done in the startup, but for simplicity we leave it here.
Once everything is configured, we proceed to create the database. There are several options, but I prefer to have everything executed when running the program. This means that if the database does not exist, it will be created.
using (var scope = app.Services.CreateScope()){ CursoEfContext context = scope.ServiceProvider.GetRequiredService<CursoEfContext>(); context.Database.EnsureCreated();}
And this is the result of running the code:
As we can see, the name
column has a varchar
with a 50 character limit, as specified by the annotations.
EnsureCreated
is designed for quickly setting up the database, for example when you're creating the first implementation of a project. For now, we'll leave it like this, but when we see migrations, we'll adjust the code a bit.
What we do with EnsureCreated
is make sure the database exists and has tables. If it doesn't have tables, it's created using the Entity Framework model you have defined, but if there are tables, even if they don't match your model, nothing will be executed.
- NOTE: You can skip this setup if you want to execute the initial configuration or migrations from the command line.
We'll leave this post here, and in the next one we will cover migrations, which is the most common way to implement code first in .NET. However, I wanted to make this post separately so the concept of code first is clear.
Conclusion
With Code First, we first create the data model in code, and then Entity Framework creates the database, tables, and relationships automatically.
Code first is very popular because it's relatively easy to maintain, especially with microservices. It is quite simple to use and thorough for designing databases.
If there is any problem you can add a comment bellow or contact me in the website's contact form