-
Notifications
You must be signed in to change notification settings - Fork 1
Updating Data
Of course to use a database, it must have data.
So it needs to be able updated with more data, edited and deleted.
The Insert method can be be used to insert data into the tables.
using (var db = new ChinookDatabase())
{
db.Albums.Insert(new Album { ArtistId = 2, Title = "Something" });
}This inserts a row into the Album table. It also returns the number of rows inserted.
This is were attributes come into play.
If your model has no attributes whatsoever, then the insert method will insert into every column there is in the object, which isn't always the best idea.
When you have an INTEGER PRIMARY KEY column, by default when you insert a new row, SQLite sets it's value to one number greater than the largest value in that column, to keep the values unique or something. This doesn't happen if a value is manually inserted into the column. So you'd want to mark that property with a PrimaryKey attribute, so that the Insert method knows not insert into that column if you the property is null or equal the default value of it's type.
Also, if you mark a property with PrimaryKey attibute and set the AutoIncrement member to true. This column will be completely untouched by Insert.
The Update method can be used to update tables.
using (var db = new ChinookDatabase())
{
var album = db.Albums.Single(a => a.AlbumId == 50);
album.Title = album.Title + " (Deluxe Edition)";
db.Albums.Update(album);
}This updates a row in the table Album with the given primary key. It also returns the number of rows affected.
The Update method can be used to update all columns of a table except the columns declared as PRIMARY KEY for obvious reasons.
If you wish to update any of the PRIMARY KEY columns, you will have to manually do it in SQL.
The Delete method can be used to delete table rows.
It takes a predicate as an argument.
using (var db = new ChinookDatabase())
{
db.Albums.Delete(a => a.ArtistId == 2);
}This deletes any rows for which the predicate is satisfied. It also returns the number of rows deleted.
- Getting Started
- Creating the Schema
- Updating data
- Querying data
- Data Types Support