Entity Framework Core
Tables, rows, relations, migrations, transactions, expression-tree queries and real entity classes — a Ring program describes the model with data and EF Core does the rest.
The idea#
A Ring program describes the model with data, because the classes of a model are .NET classes: a list of tables, each with a list of columns. EF Core works on that model in two ways:
| Class | Rows are | Best for |
|---|---|---|
RingDatabase | lists of [name, value] pairs | scripts, tools, small apps — the simplest API |
RingEntityDb | real .NET objects (classes generated from the schema) with navigation properties | change tracking, Include, an object-oriented style |
Both support SQLite (bundled), an in-memory database, and SQL Server, PostgreSQL and MySQL when their EF Core package is available.
load "dotnet.ring"
using { "RingDotNet.Data" } # loads Entity Framework Core and the RingDatabase classesA table and its rows#
The schema is a list of tables: [tableName, [ [column, type, isKey, options], ... ]]. Column types: int long double decimal string bool datetime bytes. An int or long key is generated by the database.
docs/examples/ef_basic.ring
# Entity Framework Core: a table, rows, SQL conditions
load "dotnet.ring"
using { "RingDotNet.Data" }
func main
oDb = new RingDatabase("Data Source=:memory:",[
["Customers",[
["Id","int",1],
["Name","string",0,[["required",1],["maxlength",40]]],
["Age","int",0,[["nullable",1]]],
["City","string",0,[["index",1]]]
]]
])
nAnn = oDb.insert("Customers",[["Name","Ann"],["Age",31],["City","Cairo"]])
nBob = oDb.insert("Customers",[["Name","Bob"],["Age",17],["City","Oslo"]])
oDb.insert("Customers",[["Name","Cy"],["Age",45],["City","Cairo"]])
? "keys generated: " + nAnn + ", " + nBob
? "rows: " + oDb.count("Customers")
aRow = oDb.byKey("Customers",nAnn)
? "row 1: " + dbValue(aRow,"Name") + ", " + dbValue(aRow,"Age") + ", " + dbValue(aRow,"City")
? nl + "adults in Cairo:"
aCustomers = oDb.where("Customers","Age >= {0} AND City = {1}",[18,"Cairo"])
for aCustomer in aCustomers
? " " + dbValue(aCustomer,"Name") + " (" + dbValue(aCustomer,"Age") + ")"
next
oDb.update("Customers",nBob,[["Age",18],["City","Bergen"]])
? nl + "Bob now: " + dbValue(oDb.byKey("Customers",nBob),"City")
oDb.remove("Customers",nAnn)
? "after delete: " + oDb.count("Customers") + " rows"
? "missing row: [" + oDb.byKey("Customers",99) + "]"
oDb.close()keys generated: 1, 2
rows: 3
row 1: Ann, 31, Cairo
adults in Cairo:
Ann (31)
Cy (45)
Bob now: Bergen
after delete: 2 rows
missing row: []insertreturns the key.byKeyreturns the row, or""when it does not exist.- A row is
[["Id",1],["Name","Ann"],...]; read a column withdbValue(aRow,"Name"). wheretakes SQL with{0}{1}parameters. They are real SQL parameters: there is no injection ("x' OR '1'='1"is just a string).
datetime columns are texts like "2024-03-05 10:30:00", bytes columns are hex texts (str2hex / hex2str), bool columns are 1 / 0.
Column options#
The optional fourth item of a column is a list of [name, value] options:
| Option | Meaning |
|---|---|
["required",1] | NOT NULL for text columns |
["nullable",1] | the column accepts null (a number can then be empty) |
["unique",1] | a unique index — a duplicate raises an error |
["index",1] | a plain index |
["maxlength",40] | maximum length of a text |
["default",5] | default value (numbers or text) |
["references","Authors"] | foreign key to the key of another table |
["ondelete","cascade"] | cascade, restrict, setnull, noaction |
["convert","upper"] | a value converter (see hooks) |
Several columns with isKey = 1 make a composite key: byKey("Enrollments",[studentId,courseId]).
A failed save (a unique violation, a missing required value...) raises an error and forgets its changes, so the next call starts clean; the message includes the database's own message.
Relationships#
A column with ["references","Authors"] becomes a foreign key. children, parent and include read the related rows:
docs/examples/ef_relations.ring
# Entity Framework Core: foreign keys, children, parent, include and delete behaviors
load "dotnet.ring"
using { "RingDotNet.Data" }
func main
oDb = new RingDatabase("Data Source=:memory:",[
["Authors",[["Id","int",1],["Name","string",0]]],
["Books",[["Id","int",1],["Title","string",0],["AuthorId","int",0,[["references","Authors"],["ondelete","cascade"]]]]]
])
nTolkien = oDb.insert("Authors",[["Name","Tolkien"]])
nLewis = oDb.insert("Authors",[["Name","Lewis"]])
oDb.insert("Books",[["Title","The Hobbit"],["AuthorId",nTolkien]])
oDb.insert("Books",[["Title","The Silmarillion"],["AuthorId",nTolkien]])
nNarnia = oDb.insert("Books",[["Title","Narnia"],["AuthorId",nLewis]])
? "books by Tolkien:"
aBooks = oDb.children("Authors",nTolkien,"Books")
for aBook in aBooks
? " " + dbValue(aBook,"Title")
next
? nl + "Narnia was written by " + dbValue(oDb.parent("Books",nNarnia,"Authors"),"Name")
? nl + "include:"
aItems = oDb.include("Authors","Books")
for aItem in aItems
? " " + dbValue(aItem[1],"Name") + " has " + len(aItem[2]) + " book(s)"
next
try
oDb.insert("Books",[["Title","Orphan"],["AuthorId",99]])
catch
? nl + "a foreign key to nothing is rejected"
done
oDb.remove("Authors",nLewis)
? "cascade: " + oDb.count("Books") + " books left"
oDb.close()books by Tolkien:
The Hobbit
The Silmarillion
Narnia was written by Lewis
include:
Tolkien has 2 book(s)
Lewis has 1 book(s)
a foreign key to nothing is rejected
cascade: 2 books leftQueries as data#
For anything beyond a SQL condition, describe the query as data. EF Core builds a real LINQ expression tree from it and translates it to SQL, so it works with every provider:
docs/examples/ef_queries.ring
# Entity Framework Core: queries as LINQ expression trees, aggregates and SQL of any shape
load "dotnet.ring"
using { "RingDotNet.Data" }
func main
oDb = new RingDatabase("Data Source=:memory:",[
["People",[["Id","int",1],["Name","string",0],["Age","int",0],["City","string",0],["Score","double",0]]]
])
oDb.insert("People",[["Name","Ann"],["Age",31],["City","Cairo"],["Score",8.5]])
oDb.insert("People",[["Name","Bob"],["Age",17],["City","Oslo"],["Score",6]])
oDb.insert("People",[["Name","Cy"],["Age",45],["City","Cairo"],["Score",9]])
oDb.insert("People",[["Name","Dee"],["Age",28],["City","Giza"],["Score",7.5]])
aRows = oDb.query("People",[
["where",["and",["Age",">",20],["City","in",["Cairo","Giza"]]]],
["orderby",[["Age","desc"]]],
["take",2],
["select",["Name","Age"]]
])
? "top two adults in Cairo or Giza:"
for aRow in aRows
? " " + dbValue(aRow,"Name") + " " + dbValue(aRow,"Age")
next
? nl + "count : " + oDb.countWhere("People",["City","=","Cairo"])
? "sum age : " + oDb.sum("People","Age",[])
? "average : " + oDb.average("People","Score",[])
? "max : " + oDb.max("People","Score",[])
? nl + "people per city:"
aGroups = oDb.groupCount("People","City",[])
for aGroup in aGroups
? " " + aGroup[1] + ": " + aGroup[2]
next
? nl + "any SELECT shape:"
aCityRows = oDb.sqlRows("SELECT City, COUNT(*) AS N, AVG(Age) AS AvgAge FROM People WHERE Age > {0} GROUP BY City ORDER BY City",[18])
for aRow in aCityRows
? " " + dbValue(aRow,"City") + " n=" + dbValue(aRow,"N") + " avg=" + dbValue(aRow,"AvgAge")
next
oDb.close()top two adults in Cairo or Giza:
Cy 45
Ann 31
count : 2
sum age : 121
average : 7.75
max : 9
people per city:
Cairo: 2
Giza: 1
Oslo: 1
any SELECT shape:
Cairo n=2 avg=38
Giza n=1 avg=28Conditions are [column, op, value] with op one of = != < <= > >= contains startswith endswith in isnull notnull, combined with ["and", c1, c2], ["or", c1, c2] and ["not", c]. sqlRows runs any SELECT and returns rows of any shape — joins, groups, computed columns.
Transactions and manual saving#
oDb.begin()
oDb.update("Accounts",nA,[["Balance",70]])
oDb.update("Accounts",nB,[["Balance",80]])
oDb.commit() # or oDb.rollback()
oDb.autoSave(false) # changes are written together by save()
oDb.insert("Accounts",[["Owner","D"],["Balance",5]])
oDb.insert("Accounts",[["Owner","E"],["Balance",6]])
oDb.save()
oDb.autoSave(true)The async versions return a .NET Task; dbWait waits for it and returns the result:
oTask = oDb.insertAsync("Accounts",[["Owner","F"],["Balance",7]])
? dbWait(oTask) # the key
? len(dbWait(oDb.allAsync("Accounts")))Migrations#
migrate() brings an existing database in line with the model: it creates the missing tables, columns and indexes and returns the list of changes. apply(name, sql) runs a named SQL change once and records it in the table RingMigrations.
docs/examples/ef_migrate.ring
# Entity Framework Core: migrations of an existing database file
load "dotnet.ring"
using { "System.IO" "RingDotNet.Data" }
func main
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_docs_migrate.db"])
if new File().Exists(cFile)
new File().Delete(cFile)
ok
cConnection = "Data Source=" + cFile
# version 1 of the program
oDb = new RingDatabase(cConnection,[ ["Users",[["Id","int",1],["Name","string",0]]] ])
oDb.insert("Users",[["Name","Ann"]])
oDb.close()
# version 2: a new column and a new table
oDb = new RingDatabase(cConnection,[
["Users",[["Id","int",1],["Name","string",0],["Email","string",0],["Level","int",0,[["default",3]]]]],
["Notes",[["Id","int",1],["Text","string",0],["UserId","int",0,[["references","Users"]]]]]
])
? "migrating:"
aChanges = oDb.migrate()
for cChange in aChanges
? " " + cChange
next
aRow = oDb.byKey("Users",1)
? "existing row: " + dbValue(aRow,"Name") + ", level " + dbValue(aRow,"Level")
? "named change applied: " + oDb.apply("001-promote","UPDATE Users SET Level = 9")
? "applied again: " + oDb.apply("001-promote","UPDATE Users SET Level = 1")
oDb.discard() # byKey returns the tracked row: forget it to read what the SQL changed
? "level now: " + dbValue(oDb.byKey("Users",1),"Level")
oDb.close()
new File().Delete(cFile)migrating:
add column Users.Email
add column Users.Level
create table Notes
create index IX_Notes_UserId
existing row: Ann, level 3
named change applied: 1
applied again: 0
level now: 9migrate() never drops or changes a column. For those, run SQL with execute or apply.
Hooks, filters and converters#
Ring functions can run when changes are saved or SQL is executed; a table can have a global query filter (soft delete); a column can have a value converter:
docs/examples/ef_hooks.ring
# Entity Framework Core: hooks, query filters, converters, transactions
load "dotnet.ring"
using { "RingDotNet.Data" }
aSql = []
func main
oDb = new RingDatabase("Data Source=:memory:",[
["Notes",[["Id","int",1],["Text","string",0,[["convert","upper"]]],["Deleted","int",0]],[["filter",["Deleted","=",0]]]]
])
oDb.onSaving(dnCallback("beforeSave"))
oDb.onLog(dnCallback("logSql"))
oDb.insert("Notes",[["Text","keep me"],["Deleted",0]])
oDb.insert("Notes",[["Text","soft deleted"],["Deleted",1]])
? "stored in uppercase: " + dbValue(oDb.sqlRows("SELECT Text FROM Notes",[])[1],"Text")
? "visible notes (global filter): " + len(oDb.all("Notes"))
? "all notes: " + len(oDb.query("Notes",[ ["ignorefilters",1] ]))
try
oDb.insert("Notes",[["Text","forbidden"],["Deleted",0]])
catch
? "the saving hook cancelled the save"
done
? "notes after the cancelled save: " + oDb.count("Notes")
oDb.begin()
oDb.insert("Notes",[["Text","inside a transaction"],["Deleted",0]])
oDb.rollback()
? "after rollback: " + oDb.count("Notes")
? "SQL statements logged: " + len(aSql)
oDb.close()
func beforeSave aArgs
for aChange in aArgs[1]
if dbValue(aChange[3],"Text") = "forbidden"
return "forbidden text"
ok
next
return ""
func logSql aArgs
aSql + aArgs[1]stored in uppercase: KEEP ME
visible notes (global filter): 1
all notes: 2
the saving hook cancelled the save
notes after the cancelled save: 1
after rollback: 1
SQL statements logged: 7Real entity classes#
RingEntityDb uses the same schema, but each table becomes a real .NET class with one property per column, a navigation property to the parent for each foreign key (AuthorId → Author) and a collection on the parent (Books). EF tracks the objects like it tracks classes written in C#:
docs/examples/ef_entities.ring
# Entity Framework Core with real entity classes: navigation properties, tracking, include
load "dotnet.ring"
using { "RingDotNet.Data" }
func main
oDb = new RingEntityDb("Data Source=:memory:",[
["Authors",[["Id","int",1],["Name","string",0]]],
["Books",[["Id","int",1],["Title","string",0],["Year","int",0],["AuthorId","int",0,[["references","Authors"]]]]]
])
cProperties = ""
aProperties = oDb.properties("Books")
for cProperty in aProperties
cProperties += cProperty + " "
next
? "properties of Books: " + cProperties
oTolkien = oDb.newEntity("Authors")
oTolkien.setProp("Name","Tolkien")
oDb.add(oTolkien)
? "author key: " + oTolkien.getProp("Id")
oBook = oDb.newEntity("Books")
oDb.fill(oBook,[["Title","The Hobbit"],["Year",1937]])
oBook.setProp("Author",oTolkien) # a navigation property sets the foreign key
oDb.add(oBook)
? "AuthorId of the book: " + oBook.getProp("AuthorId")
aBooks = oDb.query("Books",[ ["include",["Author"]], ["where",["Year","<",1950]] ])
for oB in aBooks
? oB.getProp("Title") + " by " + oB.getProp("Author").getProp("Name")
next
oBook.setProp("Title","The Hobbit (1st edition)") # tracked: saved by save()
oDb.save()
oDb.discard()
? "after save: " + oDb.getValue(oDb.find("Books",1),"Title")
aAuthors = oDb.query("Authors",[ ["include",["Books"]] ])
? "books of the author: " + aAuthors[1].getProp("Books").getProp("Count")
oDb.close()properties of Books: Id Title Year AuthorId Author
author key: 1
AuthorId of the book: 1
The Hobbit by Tolkien
after save: The Hobbit (1st edition)
books of the author: 1Providers#
The connection text selects the provider:
| Connection | Provider |
|---|---|
"Data Source=people.db" | SQLite (bundled). "Data Source=:memory:" for an in-memory SQLite database |
"inmemory:name" | the EF in-memory provider (no SQL, no migrations; same name = same database) |
"sqlserver:Server=.;Database=x;..." | SQL Server — needs Microsoft.EntityFrameworkCore.SqlServer.dll next to the other assemblies |
"postgres:Host=...;..." | PostgreSQL (Npgsql provider) |
"mysql:Server=...;..." | MySQL (Pomelo provider) |
The SQL Server, PostgreSQL and MySQL providers are loaded by name from their NuGet packages and have not been tested here. SQLite and the in-memory provider are tested.
The full EF API#
Everything in EF Core is also wrapped as classes (using { "Microsoft.EntityFrameworkCore" }, .ChangeTracking, .Infrastructure, .Metadata, .Metadata.Builders, .Storage, .Query, .Migrations, .Diagnostics, Microsoft.Data.Sqlite; clashing names start with Ef). oDb.context() returns the real DbContext:
oContext = oDb.context()
? oContext.Database.ProviderName # Microsoft.EntityFrameworkCore.SqliteThe complete list of methods is in the Entity Framework reference. A complete program: samples/UsingDotNet/applications/Contacts — a contacts book with a console menu.
Where to go next#
- Entity Framework reference: every method and option.
- The tutorial chapter Databases and services.