Entity Framework Core 8 for NTi
OVERVIEW
Entity Framework Core for NTi is an ORM (Object-Relational Mapper), designed to exploit the capabilities of DB2 for i databases (DB2/400 or DB2 iSeries) on IBM i. It provides .NET developers with a familiar, high-performance interface for interacting with DB2 for i. With EF Core for NTi, you can:
- Use DB2 for i with modern .NET tools to develop new applications at lightning speed, whether you're starting from scratch (code first) or from an existing database (DB First).
- Simplify your developments by interacting with your data directly via LINQ, without having to write SQL.
- Develop on several platforms (Windows, Linux or macOS.)
This documentation does not cover in detail the general concepts of the entity Framework Core, which are standardised. For advanced notions and best practices of EF Core, consult the official Microsoft documentation
PREREQUISITES AND INSTALLATION
PREREQUISITES
- .NET SDK 8.
- Visual Studio 2022 or equivalent.
- A DB2 for i database.
INSTALLATION
Add the NuGet Aumerial.EntityFrameworkCore
package, either directly using the NuGet package management interface in visual Studio, or via the command line interface of your code editor.
dotnet add package Aumerial.EntityFrameworkCore
Then import the namespace to use EntityFramework Core
in your project
using Aumerial.EntityFrameworkCore
💡 For migrations and scaffolding, use only Microsoft.EntityFrameworkCore.Design version 8.0.X to ensure compatibility with NTi EF Core and .NET 8.
DbContext
Configuration
Create a class inheriting from DbContext
, which will define the entities and configurations of your database.
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
// Add your DbSet here
public DbSet<MyEntity> MyEntities { get; set; }
}
In a Web Project, use dependency injection, and save your DbContext
in the Program.cs
file.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext(options =>
options.UseNti(connectionString));
💡 For asynchronous tasks or background services, use
AddDbContextFactory
.
MANAGEMENT OF SPECIFIC DATA TYPES
- Support for BLOB types
You can store files or images directly in your IBM i database using columns of type BLOB.
[Column(TypeName = "BLOB(1M)"), DataType(DataType.Upload)]
public byte[] ProfilePhoto { get; set; }
- Global Length Configuration
You can set a default length for the varchar, varbinary, and vargraphic types when registering your Dbcontext
.
builder.Services.AddDbContextFactory<AppDbContext>(
options =>
options.UseNTi(connectionString, opt => opt.VarfieldMaxLength(1024, 256, 512)));
- 1024 : Default length for VARCHAR
- 256 : for VARBINARY
- 512 : for VARGRAPHIC
You can also specify the length directly in your entities using the [MaxLenght] attribute.
[Column(TypeName = "VARCHAR"), MaxLength(128)]
public string Description { get; set; }
Creation of Entities and Migration (Code First)
When working with NTi EF Core to create tables from scratch, start by choosing a schema to organise your tables, define your entities in the code and apply the migrations.
- **Choose Schema **
Add a default schema to your connection string to ensure that all tables created are placed in this schema.
server=myserver;user=myuser;password=mypassword;database=mydb;database=MYSCHEMA;
If you need to place certain tables in specific schemas, configure them explicitly in the DbContext
:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().ToTable("Product", "MYSCHEMA");
modelBuilder.Entity<Order>().ToTable("Order", "MYSCHEMA");
}
- Define your entities
Create classes to represent your tables.
public class Order
{
public int Id { get; set; }
public DateTime OrderDate { get; set; }
public decimal TotalAmount { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public List<Order> Orders { get; set; } // Relationship with orders
}
Add these entities to your DbContext :
public DbSet<Order> Orders { get; set; }
public DbSet<Product> Products { get; set; }
- Generate and Apply a Migration
Create an initial migration which will generate a migration file containing the SQL statements needed to create the tables defined in your entities:
dotnet ef migrations add InitialCreate
Then apply the Migration, and update the database to apply the changes and create the tables:
dotnet ef database update
Retrieving entities from an existing database (DB First)
To retrieve the schema of an existing database and generate the corresponding entities, create an empty DbContext
class:
public class MyDbContext : DbContext {
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }
}
Then run the Scaffold Command
dotnet ef dbcontext scaffold "server=myserver;user=myuser;password=mypassword;database=mydb" Aumerial.EntityFrameworkCore --output-dir Data/Models --schema mydb
- --output -dir: specifies the location of generated entities (e.g. Data/Models).
- --schema: specifies the schema to be retrieved (e.g. myschema)
If no migration has yet been created, generate an empty initial migration:
dotnet ef migrations add InitialCreate
Empty "up" and "down" in the generated file to avoid automatic changes.
protected override void Up(MigrationBuilder migrationBuilder)
{
// Leave blank
}
protected override void Down(MigrationBuilder migrationBuilder) {
// Leave blank
}
This avoids accidentally deleting or recreating existing tables when applying migrations..
Create a C# class to represent the new table, or add or modify a property on an existing entity.
public class MyNewTable {
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreatedAt { get; set; }
}
Add this entity to the DbContext
:
public DbSet<MyNewTables> MyNewTables { get; set; }
Generate the new Migration for this table:
dotnet ef migrations add AddMyNewTable
Then update the database to include the new table by applying migration.
dotnet ef database update
Automatic CRUD generation (existing entities)
If your entities are already defined in your project, you can automatically generate CRUD pages or components using Visual Studio's integrated tools or using Entity Framework Core.
For a Blazor Server application
Creation of a CRUD component.
Right-click on the Pages folder in your Blazor Server project.
Select : Add > Automatically generated new element > Razor components with Entity Framework (CRUD).
Configuring Options
- Model Class : Select an existing entity (for example, Product).
- DbContext class : Select your DbContext (for example, AppDbContext).
Visual Studio automatically generates a set of Razor CRUD components in a dedicated folder (for example, ProductsPages), with the following files:
- Index.razor : List of recordings.
- Create.razor : Form to add a new record.
- Edit.razor : Form for modifying an existing record.
- Details.razor : Displays the details of a recording.
- Delete.razor : Confirm and delete a recording.