Connect Using the Microsoft Entity Framework Core (EF Core)
Create and debug an EF Core application that connects to SAP HANA.
Overview
You will learn
- How to install the .NET Core EF CLI
- How to create and debug an EF Core application that queries an SAP HANA database
- How to use the scaffold command to generate entity classes for pre-existing schema tables
Prerequisites
Prerequisites
- You have completed the first 3 tutorials in this mission
- You have completed the previous tutorial on .NET in this mission
Steps
Intro
.NET is a free and open-source software framework for Microsoft Windows, Linux, and Mac operating systems and is the successor to the .NET Framework. Entity Framework Core is a modern object-database mapper for .NET and can reduce data access code in an application.
The dotnet tool command can be used to install and manage tools that extend .NET. The following are a few examples that can be run to show help, to list the local and globally installed tools, to uninstall dotnet-ef if an incompatible version is installed, and to search the repository for version details of the dotnet-ef tool.
dotnet tool -h
dotnet tool list -h
dotnet tool list
dotnet tool list -g
dotnet tool uninstall dotnet-ef -g
dotnet tool search dotnet-ef --detailThe SAP HANA Client 2.28 release supports EF Core 9.0 among other versions. For a list versions and support dates see EF Core releases and planning and SAP Note 3165810 - SAP HANA Client Supported Platforms.
Run the following command to install version 9 of the dotnet-ef tool.
dotnet tool install dotnet-ef --version 9.0.14 -g
dotnet tool list -g
The help for the .NET Command Line Tools can be displayed as shown below.
dotnet ef -h
Create a new console app with the below commands:
Shellcd %HOMEPATH%/HANAClientsTutorial dotnet new console -o EFCoreShellcd $HOME/HANAClientsTutorial dotnet new console -o EFCoreAdd the required packages including the SAP HANA .NET data provider which is available on nuget. A list of available providers from SAP is available at SAP-SE.
Shellcd EFCore dotnet add package Sap.EntityFrameworkCore.Hana.v9.0 dotnet add package Microsoft.EntityFrameworkCore.Relational --version 9.0.14
HANAClientDriverDownload The packages can be listed using the command below.
Shelldotnet list packageRun the app to validate that SAP hdbclient DLLs can be loaded:
Shelldotnet runThe expected output is
Hello, World!.Open an editor and create a file named
HotelModel.cs.Shellnotepad HotelModel.csShellpico HotelModel.csCopy the below code into
HotelModel.cswith the code below:C#using Microsoft.EntityFrameworkCore; using Sap.EntityFrameworkCore.Hana; public class HotelContext : DbContext { public DbSet<HotelEF> Hotel { get; set; } public HotelContext() { var folder = Environment.SpecialFolder.LocalApplicationData; var path = Environment.GetFolderPath(folder); Database.EnsureDeleted(); Database.EnsureCreated(); } protected override void OnConfiguring(DbContextOptionsBuilder options) { options.UseHana("Server=xxxxxxxx-.hanacloud.ondemand.com:443;UserName=User2;Password=Password2;Current Schema=USER2"); } } public class HotelEF { public int Id { get; set; } = 0; public string Name { get; set; } = string.Empty; public string Address { get; set; } = string.Empty; }Be sure to update the host URL and optionally the user name and password. Note that calls to EnsureDeleted and EnsureCreated will delete and recreate the objects in the schema USER2. As documented at RelationalDatabaseCreator.EnsureDeleted Method, it will delete all objects in the schema USER2.
Open an editor to edit the file
Program.cs.Shellnotepad Program.csShellpico Program.csReplace the entire contents of
Program.cswith the code below. Save and close the file when finished.C#using var db = new HotelContext(); // Create Console.WriteLine("Inserting a new Hotel"); db.Add(new HotelEF { Id = 1, Name = "The Inn of Waterloo", Address = "475 King St N, Waterloo" }); db.Add(new HotelEF { Id = 2, Name = "The Walper Hotel", Address = "20 Queen St S, Kitchener" }); db.SaveChanges(); // Read Console.WriteLine("Querying for a hotel"); var hotels = db.Hotel .OrderBy(b => b.Name).Last(); Console.WriteLine("Found: " + hotels.Name);Further details on SAP HANA Client entity core driver can be found at Entity Framework Core Support. Further .NET API details can be found in the .NET API browser.
Run the app:
Shelldotnet runBefore running the program make sure to be in the directory where Program.cs is saved

Result of running the app
Open Visual Studio Code. If needed, download the application here.
If you have not already done so, choose File | Add Folder to Workspace, and then add the
HANAClientsTutorialfolder.
Workspace Open the file
Program.csand set a breakpoint.Select Run | Start Debugging | .NET Core. A configuration will be added. Choose Run | Start Debugging.
Notice that the debug view becomes active and that the RUN option is .NET Launch.
Notice that the program stops running at the breakpoint that was set.
Observe the variable values in the leftmost pane. Step through code.

VS Code Debugging For further information on debugging .NET apps consult Tutorial: Debug a .NET Core console application using Visual Studio Code and Instructions for setting up the .NET Core debugger.
The following steps demonstrate the process of generating entity type classes and a DbContext class based on an existing database schema. Additional details can be found at Scaffolding (Reverse Engineering).
Create a new console app with the below commands:
Shellcd %HOMEPATH%/HANAClientsTutorial dotnet new console -o EFCoreScaffoldShellcd $HOME/HANAClientsTutorial dotnet new console -o EFCoreScaffoldInstall the required packages.
Shellcd EFCoreScaffold dotnet add package Sap.EntityFrameworkCore.Hana.v9.0 dotnet add package Microsoft.EntityFrameworkCore.Relational --version 9.0.14 dotnet add package Microsoft.EntityFrameworkCore.Design --version 9.0.14The list of installed packages can be seen using the below command.
Shelldotnet list package
package list Additional details can be found at dotnet add package and Microsoft.EntityFrameworkCore.Design
Use the scaffold command to generate entity classes for the HOTELS schema. Update the SQL endpoint.
Shelldotnet ef dbcontext scaffold "Server=xxxxxxxx-.hanacloud.ondemand.com:443;uid=USER2;pwd=Password2;Current Schema=HOTELS" Sap.EntityFrameworkCore.Hana.v9.0 --schema HOTELS --context HotelsContextNotice that classes have been generated for each object in the schema HOTELS.

scaffold command Should you wish to regenerate the files in the future and overwrite the existing files, the
--forceparameter can be used. Additional details on the scaffold command can be found at .NET Core CLI.Open an editor to edit the file
Program.cs.Shellnotepad Program.csShellpico Program.csReplace the entire contents of
Program.cswith the code below. Save and close the file when finished.C#using EFCoreScaffold; using var db = new MyHotelsContext(true); // Create Console.WriteLine("Inserting a new maintenance item"); db.Add(new Maintenance { Mno = 3, Description = "Replace cracked mirror in lobby bathroom" }); db.SaveChanges(); // Read Console.WriteLine("Querying for a maintenance item"); var maintenanceItems = db.Maintenances .OrderBy(b => b.Hno).Last(); Console.WriteLine("Found item#: " + maintenanceItems.Mno + " Desc: " + maintenanceItems.Description);Open an editor to edit the file
HotelsContext.cs.Shellnotepad HotelsContext.csShellpico HotelsContext.csDelete the
OnConfiguringmethod. This will be added to theMyHotelsContext.csclass.Open an editor to create and edit a new file named
MyHotelsContext.cs.Shellnotepad MyHotelsContext.csShellpico MyHotelsContext.csAdd the code below. Update the Server= line to match your SAP HANA Cloud SQL endpoint. Save and close the file when finished. Note that the schema is changed to be USER2.
C#using Microsoft.EntityFrameworkCore; using Sap.EntityFrameworkCore.Hana; namespace EFCoreScaffold; internal class MyHotelsContext : HotelsContext { public MyHotelsContext(bool createTables) : base() { if (createTables) { // Delete the existing database tables and re-create new tables. Database.EnsureDeleted(); Database.EnsureCreated(); } } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseHana("Server=xxxxxxxx-.hanacloud.ondemand.com:443;uid=USER2;pwd=Password2;Current Schema=USER2"); } }Run the app:
Shelldotnet run
Result of running the app Notice that tables such as CUSTOMER, HOTEL, MAINTENANCE etc have now been created in the USER2 schema.

tables in user2 schema
Congratulations! You have now created and debugged a .NET application that connects to and queries an SAP HANA database.
Resources
Discussion
Share feedback on this tutorial or join the conversation in SAP Community.