Getting Started With Entity Framework Core (2024)

This walkthrough demonstrates the minimum required to create a database using Entity Framework Core in a .Net Core Console application. The walkthrough assumes that you have .Net Core SDK installed and that you have a suitable development environment/text editor. Visual Studio Code will be used in this example.

Creating a .NET Core Console application

If you have a version of Visual Studio that supports .Net Core (2017 or greater), you can use the project templates to create a new .Net Core console application. Alternatively, you can use a command line tool to create and build the project. You can use the Terminal that's integrated into Visual Studio Code for this.

Create a folder named EFCoreDemo and then open it in Visual Studio Code.

Press Ctrl + ' to open a new Terminal window and then type the following commands:

language-cmd

|

> dotnet new console > dotnet add package Microsoft.EntityFrameworkCore.SqlServer> dotnet add package Microsoft.EntityFrameworkCore.Tools 

The commands above

  • scaffolds a blank .NET Core console application
  • adds the Entity FrameworkCore and EF Core tooling packages from Nuget to the project

Now modify the .csproj file to include the following additional <ItemGroup> is added to the project. This may not have been added automatically:

language-xml

|

 <ItemGroup> <DotNetcl*toolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" /> </ItemGroup>

Finally, run the following command to restore the packages and then test to see that the ef commands are available to the project:

language-cmd

|

> dotnet restore > dotnet ef -h 

This should result in the initial help for the EF tools being displayed:

Getting Started With Entity Framework Core (1)

Finally, build and run the application with the single command:

language-cmd

|

> dotnet run

This results in a minimal console application:

Getting Started With Entity Framework Core (2)

Creating A Model

Add a new file named EFCoreDemoContext.cs and add the following code to it:

language-csharp

|

using Microsoft.EntityFrameworkCore;namespace EFCoreDemo{ public class EFCoreDemoContext : DbContext { public DbSet<Book> Books { get; set; } public DbSet<Author> Authors { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=.\;Database=EFCoreDemo;Trusted_Connection=True;MultipleActiveResultSets=true"); } }}

Note: The model, particularly the DbContext class, is declared inside a namespace. If you don't place your context class in a namespace and you are working with EF Core versions before 2.1, you may come up against this bug - now fixed in 2.1 when adding your migration.

Next, add a new file named Author.cs and add the following code to it:

language-csharp

|

using System.Collections.Generic;namespace EFCoreDemo{ public class Author { public int AuthorId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public ICollection<Book> Books { get; set; } = new List<Book>(); }}

Finally, add a new file named Book.cs and add the following code to it:

language-csharp

|

namespace EFCoreDemo{ public class Book { public int BookId { get; set; } public string Title { get; set; } public int AuthorId { get; set; } public Author Author { get; set; } }}

This code defines classes for two entities - Book and Author that participate in a fully defined one-to-many relationship. The code also includes a class named EFCoreDemoContext that inherits from DbContext. This class has two DbSet properties that represent the tables in the database (which are yet to be created). The EFCoreDemoContext class also includes a method named OnConfiguring where the connection string for a SQL Server database is defined. You should change this to suit your environment and database provider.

Adding A Migration

Migrations are used to keep the database schema in sync with the model. There is no database at the moment, so the first migration will create it and add tables for the entities represented by the DbSet properties on the EFCoreDemoContext that you added.

Enter the following command in the Terminal window:

language-cmd

|

dotnet ef migrations add CreateDatabase

A new folder named Migrations is added to the project. It contains the code for the migration and a model snapshot.

Getting Started With Entity Framework Core (3)

Enter the following command to execute the migration:

language-cmd

|

dotnet ef database update

The database is created but all of the string fields are unlimited in size (nvarchar(MAX) in SQL Server).

Getting Started With Entity Framework Core (4)

Modifying The Database With Migrations

In the next section, you will modify the model to set limits to the size of selected string properties, and then use migrations to push those changes to the database schema.

Add the following to the using directives at the top of Author.cs and Book.cs:

language-csharp

|

using System.ComponentModel.DataAnnotations;

Modify the Book and Author entities so that they look like this:

language-csharp

|

public class Book{ public int BookId { get; set; } [StringLength(255)] public string Title { get; set; } public int AuthorId { get; set; } public Author Author { get; set; }}

language-csharp

|

public class Author{ public int AuthorId { get; set; } [StringLength(50)] public string FirstName { get; set; } [StringLength(75)] public string LastName { get; set; } public ICollection<Book> Books { get; set; } = new List<Book>();}

In the Terminal, type the following command:

language-cmd

|

dotnet ef migrations add LimitStrings

followed by

language-cmd

|

dotnet ef database update

This will scaffold a migration that will alter the size of the Book's Title field and the Author's FirstName and LastName fields. You should also get a warning that the scaffolded migration could lead to data loss. In this case, there is no data to be lost so the warning can be ignored.

Once the migration has been applied, the database schema will be altered. Here's how the modified Author table should look:

Getting Started With Entity Framework Core (5)

Working With Data

Open the Program.cs file and replace the existing content with the following:

language-csharp

|

using System.Collections.Generic;namespace EFCoreDemo{ class Program { static void Main(string[] args) { using (var context = new EFCoreDemoContext()) { var author = new Author { FirstName = "William", LastName = "Shakespeare", Books = new List<Book> { new Book { Title = "Hamlet"}, new Book { Title = "Othello" }, new Book { Title = "MacBeth" } } }; context.Add(author); context.SaveChanges(); } } }}

Execute the following command from the command line:

language-cmd

|

dotnet run

This will cause the code in the console application's Main method to execute, and the author and all books will be added to the database. You can verify this by querying the Books table using your preferred database management tool:

Getting Started With Entity Framework Core (6)

You can also verify it by changing the content of Program.cs as follows:

language-csharp

|

using static System.Console;namespace EfCoreDemo{ class Program { static void Main(string[] args) { using (var context = new EFCoreDemoContext()) { foreach(var book in context.Books) { WriteLine(book.Title); } } } }}

Then execute the following command from the Terminal:

language-cmd

|

dotnet run

All going well, this should result in the titles of all three books being printed to the console window:

Getting Started With Entity Framework Core (7)

Getting Started With Entity Framework Core (2024)
Top Articles
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 6436

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.