RingDotNetfor Ring

Entity objects and migrations

Work with the rows of your tables as real objects that EF Core tracks, and change a database that already holds data without losing it.

What you will learn#

Two styles, one schema#

The tutorial Databases step by step used RingDatabase: a row is a list of [column, value] pairs. RingEntityDb uses the same schema but turns each table into a real .NET class. A row is an object; related rows are properties of the object.

RingDatabaseRingEntityDb
a row[["Name","Ann"],["Goals",5]]an object: oPlayer.getProp("Name")
a related rowparent(...), children(...)oPlayer.getProp("Team"), oTeam.getProp("Players")
changingupdate(table, key, values)oPlayer.setProp("Goals",8) then save()
best forscripts, quick toolsprograms that work with objects for a while

Part 1: objects#

samples/UsingDotNet/tutorials/ch09_entities.ring
# the tutorial "Entity objects and migrations", part 1: entity objects - the rows of a table as real objects with navigation properties
load "dotnet.ring"

using { "RingDotNet.Data" }

func main

	# The schema is the same as with RingDatabase. RingEntityDb turns every table into a .NET class.
	oDb = new RingEntityDb("Data Source=:memory:",[
		["Teams",[["Id","int",1],["Name","string",0,[["required",1]]]]],
		["Players",[["Id","int",1],["Name","string",0],["Goals","int",0,[["default",0]]],["TeamId","int",0,[["references","Teams"]]]]]
	])

	# The generated class has a property for every column, plus navigations that follow the foreign keys
	cProperties = ""
	aProperties = oDb.properties("Players")
	for cProperty in aProperties
		cProperties += cProperty + " "
	next
	? "Properties of a Player : " + cProperties
	cProperties = ""
	aProperties = oDb.properties("Teams")
	for cProperty in aProperties
		cProperties += cProperty + " "
	next
	? "Properties of a Team   : " + cProperties

	# STEP 1. Create objects: newEntity gives an empty object; set its properties; add() stores it
	oRed = oDb.newEntity("Teams")
	oRed.setProp("Name","Red")
	oDb.add(oRed)
	? nl + "STEP 1: the team got its key from the database: Id = " + oRed.getProp("Id")

	oAnn = oDb.newEntity("Players")
	oDb.fill(oAnn,[["Name","Ann"],["Goals",5]])
	oAnn.setProp("Team",oRed)                       # a navigation property: the foreign key is set for you
	oDb.add(oAnn)
	? "        Ann's TeamId   = " + oAnn.getProp("TeamId")

	oBob = oDb.newEntity("Players")
	oDb.fill(oBob,[["Name","Bob"],["Goals",2],["TeamId",1]])    # or set the foreign key directly
	oDb.add(oBob)
	? "        players stored : " + oDb.count("Players",[])

	# STEP 2. Read objects, with the related object loaded (include)
	? nl + "STEP 2: players with goals >= 3, with their team:"
	aPlayers = oDb.query("Players",[ ["where",["Goals",">=",3]], ["include",["Team"]] ])
	for oPlayer in aPlayers
		? "        " + oPlayer.getProp("Name") + " plays for " + oPlayer.getProp("Team").getProp("Name")
	next

	# STEP 3. Objects are TRACKED: change a property, call save(), the change is written
	oAnn.setProp("Goals",8)
	oDb.save()
	oDb.discard()                                    # forget the tracked objects, so that the next read comes from the database
	? nl + "STEP 3: Ann's goals in the database: " + oDb.getValue(oDb.find("Players",1),"Goals")

	# STEP 4. The other direction: a team with its players
	aTeams = oDb.query("Teams",[ ["include",["Players"]] ])
	for oTeam in aTeams
		? nl + "STEP 4: team " + oTeam.getProp("Name") + " has " + oTeam.getProp("Players").Count + " players"
	next

	# STEP 5. Remove an object
	oDb.remove(oDb.find("Players",2))
	? "STEP 5: after removing Bob there are " + oDb.count("Players",[]) + " player(s)"
	oDb.close()
Output
Properties of a Player : Id Name Goals TeamId Team 
Properties of a Team   : Id Name Players 

STEP 1: the team got its key from the database: Id = 1
        Ann's TeamId   = 1
        players stored : 2

STEP 2: players with goals >= 3, with their team:
        Ann plays for Red

STEP 3: Ann's goals in the database: 8

STEP 4: team Red has 2 players
STEP 5: after removing Bob there are 1 player(s)
Note

This program uses a few generic functions (getProp, setProp) where a class cannot be used. The lesson The generic functions explains them.

How it works#

Properties. oDb.properties("Players") lists them: one per column (Id Name Goals TeamId) and one navigation (Team), generated from the foreign key TeamId. The team has Players, a collection of its players.

Create. newEntity("Teams") gives an empty object, setProp sets a property, add stores it and fills in the key. For a player, oAnn.setProp("Team", oRed) sets the navigation, and EF fills in TeamId itself (1). You can also set TeamId directly.

Read. query(table, spec) returns objects. ["include",["Team"]] loads the related team in the same query; without it the navigation is empty. Read it with oPlayer.getProp("Team").getProp("Name").

Tracked. EF remembers the objects it gave you. Change one (setProp("Goals",8)) and call save(): EF finds the change and writes only that. discard() forgets the tracked objects, so that the next find reads from the database again — the program uses it to prove that the change really reached the database.

Collections. oTeam.getProp("Players") is a .NET collection: getProp("Count") and toList() work on it.

Part 2: migrations#

You shipped version 1 of a program. Users have data. In version 2 you need a Phone column and a Notes table. If you only change the schema in the program, the old file still has the old tables: new code meets old data. A migration brings the file up to date.

samples/UsingDotNet/tutorials/ch09_migrations.ring
# the tutorial "Entity objects and migrations", part 2: changing a database that already has data - migrations
load "dotnet.ring"

using {
	"System.IO"
	"RingDotNet.Data"
}

func main

	cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_migrations.db"])
	if new File().Exists(cFile)
		new File().Delete(cFile)
	ok
	cConnection = "Data Source=" + cFile

	# VERSION 1 of the program: a table of contacts with a name
	oDb = new RingDatabase(cConnection,[
		["Contacts",[["Id","int",1],["Name","string",0]]]
	])
	oDb.insert("Contacts",[["Name","Ann"]])
	oDb.insert("Contacts",[["Name","Bob"]])
	? "VERSION 1: " + oDb.count("Contacts") + " contacts stored in the file"
	oDb.close()

	# VERSION 2: you want a Phone column, a Notes table, and an index on Name.
	# Opening the OLD file with the NEW schema is not enough: the file still has the old tables.
	oDb = new RingDatabase(cConnection,[
		["Contacts",[["Id","int",1],["Name","string",0,[["index",1]]],["Phone","string",0],["Level","int",0,[["default",1]]]]],
		["Notes",[["Id","int",1],["Text","string",0],["ContactId","int",0,[["references","Contacts"]]]]]
	])

	# migrate() compares the file with the schema and makes what is missing. The old rows are kept.
	aChanges = oDb.migrate()
	? nl + "VERSION 2: migrate() made " + len(aChanges) + " changes:"
	for cChange in aChanges
		? "   " + cChange
	next
	aOld = oDb.byKey("Contacts",1)
	? nl + "The old row is still there: " + dbValue(aOld,"Name") + ", phone [" + dbValue(aOld,"Phone") + "], level " + dbValue(aOld,"Level")

	# Now the new columns and the new table work
	oDb.update("Contacts",1,[["Phone","555-0100"]])
	oDb.insert("Notes",[["Text","met at the conference"],["ContactId",1]])
	? "Ann's phone: " + dbValue(oDb.byKey("Contacts",1),"Phone") + ", notes: " + len(oDb.children("Contacts",1,"Notes"))

	# Migrating again changes nothing
	? "Migrating again: " + len(oDb.migrate()) + " changes"

	# A change that is not a new column or table is done with SQL, once, by name.
	? nl + "Promote everybody (first time) : " + oDb.apply("001-promote","UPDATE Contacts SET Level = 5")
	? "Promote everybody (second time): " + oDb.apply("001-promote","UPDATE Contacts SET Level = 9")
	oDb.discard()
	? "Level now: " + dbValue(oDb.byKey("Contacts",1),"Level") + " (the second one did not run)"
	? "Applied changes: " + oDb.applied()[1]
	oDb.close()
	new File().Delete(cFile)
Output
VERSION 1: 2 contacts stored in the file

VERSION 2: migrate() made 5 changes:
   add column Contacts.Phone
   add column Contacts.Level
   create table Notes
   create index IX_Contacts_Name
   create index IX_Notes_ContactId

The old row is still there: Ann, phone [], level 1
Ann's phone: 555-0100, notes: 1
Migrating again: 0 changes

Promote everybody (first time) : 1
Promote everybody (second time): 0
Level now: 5 (the second one did not run)
Applied changes: 001-promote

How it works#

Note

migrate() never drops or changes a column. Removing a column is a decision about losing data: do it deliberately with apply and your own SQL. migrate works for SQLite files.

Tip

byKey returns the tracked row. After a raw SQL change (apply, execute) call discard() before reading, or you will see the old values.

What you learned#

Exercises#

  1. Add a Matches table (two teams, a score) and print every match with both team names.
  2. Move a player to another team by changing the Team navigation and saving.
  3. Add a Email column in version 3 and write the migration steps.
  4. Count the goals of each team with a for loop over query("Teams", [["include",["Players"]]]).

Next#

Microsoft Access databases

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.