Database: Examples
Let's discuss some examples of communicating with the database.
We'll cover the following...
- Examples
- Adding items to a database
- Display results
- Using The Where query to display results
- The Contains keyword
- The OrderBy keyword
- The Max value
- The Remove and SaveChanges keywords
- Using Select on columns
- Using Where and Select on multiple columns
- The Single, SingleOrDefault, First, and FirstOrDefault
- Using join on multiple tables to display results
- Full Example
Examples
Let’s see some examples of manipulating the database with the C# code.
Adding items to a database
Below is an example of adding items to a database by code. Adding this code snippet to the Main
method of Program.cs
adds the two students every time the application is loaded. For the code snippet below to work, add two using
statements, using StudentDB.Data;
and using StudentDB.People;
, to the top of the page.
using (var db = new StudentDBContext())
{
// Add the following students to Database
db.Students.AddRange(new Student { Name = "Wyatt", Grade = 95 },
new Student { Name= "Kristen", Grade = 98 });
// Save the changes
db.SaveChanges();
}
Display results
In the example below, a foreach
loop is used to loop through an entire database table and display the results.
using (var db = new StudentDBContext())
{
foreach (var theStudent in db.Students)
{
Console.WriteLine($"Name: {theStudent.Name} Grade: {theStudent.Grade}");
}
}