Database: Examples

Let's discuss some examples of communicating with the database.

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}");
  } 
}

Using The Where query to

...