In this post, we are going to look at how to approach the code first paradigm in Entity Framework Core. For those of you who aren’t familiar with Entity Framework, it is a Microsoft framework that makes it easier to create database applications, 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 you design and program your data model classes in code, and then Entity Framework Core creates the database or the corresponding tables from those classes.
For this post, we are going to 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 - Implement 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 that 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 on the properties, in this case a database limit of 50 characters on the "name" column.
Now, before continuing, we install Microsoft.EntityFrameworkCore.Design
and the MySQL package because my database is MySQL. If you are using SqlServer or a different database, this second package will be different.
Next, we create the class that inherits from DbContext
and that defines the database instance 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 DbContext we have configured both the tables and the database connection, although that part, can be done in startup, but for simplicity we leave it here.
Once we have everything configured, we move on to creating the database. There are several options, but I like for everything to execute when the program runs. 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 after running the code:
As we can see, the name
column has the varchar
type with a limit of 50 characters, just as we specified with the annotations.
EnsureCreated
is designed to set up the database very quickly, for example when you are creating the first implementation of a project. For now, we are going to leave it as is, but when we get to migrations, we will change the code a little.
What we do with EnsureCreated
is make sure the database exists and has tables. If it doesn’t have tables, it will execute based on the Entity Framework model you have defined. But if it already has tables, even if they are not the exact same as in your model, nothing will be done.
- NOTE: You can skip this setup if you want to run the initial setup or migrations from the command line.
Let's end this post here. In the next one, we’ll cover migrations, which is the most common way to implement code first in .NET. But 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 is relatively easy to maintain, especially in microservices. It's quite simple to use and complete for designing databases.
If there is any problem you can add a comment bellow or contact me in the website's contact form