Entity Framework

  1. Overview
    1. Entity Framework (EF) is an object-relational mapper (ORM) that enables .NET apps to work with relational data using domain-specific objects
    2. EF allows the programmer to access and modify objects that are automatically persisted in a relational database without having to write any of the database code
    3. Many popular relational databases are supported including SQL Server, SQLite, MySQL, etc.
    4. Most recent version of EF is called EF Core
    5. Tutorial: Getting Started with EF Core
    6. Dr. McCown's Movie Theater demo on Github
  2. Project setup
    1. Create a Blank App (Universal Windows) project called EntityFrameworkDemo
    2. Use NuGet Package Manager to install Microsoft.EntityFrameworkCore.Sqlite version 3.1.21 (latest version will not work with UWP)
  3. Data Model
    1. Create a project folder called Models
    2. Add a class to Models called MovieTheaterContext
    3. Make new class inherit DbContext
      1. A DbContext instance represents a database session and is used to query and save entity instances
      2. Override OnConfiguring() to configures the database. DbContextOptionsBuilder carries configuration information for DbContext and provides methods to select a database like UseSqlServer() or UseSqlite()
      3. Create a DbSet for each entity, which maps to a database table. Has methods Add(), Update(), Remove() and can be treated as a collection to loop through all rows in the associated table
    4. Example MovieTheaterContext class creates a DbSet of Movie objects to store a list of movies; uses Sqlite database
      using Microsoft.EntityFrameworkCore;
      
      namespace EntityFrameworkDemo.Models
      {
          public class MovieTheaterContext : DbContext
          {
      		// Binds to Movies table 
              public DbSet<Movie> Movies { get; set; }
      
              protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
              {	
                  // Path accessible via ApplicationData.Current.LocalFolder.Path        
                  // Example path: C:\Users\USERNAME\AppData\Local\Packages\KEY\LocalState\theater.db
                  optionsBuilder.UseSqlite("Data Source=theater.db");
              }
          }
      }
      
    5. Add Movie class to Models folder
      1. Public properties define columns of Movies table
      2. Implements INotifyPropertyChanged to support UI data binding
    6. using System.ComponentModel;
      
      namespace EntityFrameworkDemo.Models
      {
          // All public properties of Movie are converted into table columns
          public class Movie 
          {
              // Automatically uses Id as the table's primary key (auto-increment)
              public int Id { get; set; }
      
              public string Title { get; set; }
              public string Rating { get; set; }
          }
      }
      
    7. More info: Creating and configuring a Model
  4. Create the database
    1. MovieTheater.UWP - Blank App (Universal Windows) project
    2. Add reference to data model in App.xaml.cs
    3. Use using statement with DbContext to ensure correct use of IDisposable objects
    4. Call DbContext.Database.EnsureCreated() when the app starts to create the database if it doesn't exist
      // App.xaml.cs
      
      using EntityFrameworkDemo.Models;
      ...
      
      namespace MovieTheater.UWP
      {
      	sealed partial class App : Application
          {
      		public App()
      		{
      			this.InitializeComponent();
      			this.Suspending += OnSuspending;
      
      			using (var db = new MovieTheaterContext())
      			{
      				// Create database 
      				db.Database.EnsureCreated();
      			}
      		}
      		...
      	}
      }
      
  5. Implement CRUD operations in MainPage.xaml.cs
    1. Create - Add a new movie
      var movie = new Movie
      {
      	Title = "Tron Legacy",
      	Rating = "PG-13"
      };
      	
      using (var db = new MovieTheaterContext())
      {	
      	db.Movies.Add(movie);
      	
      	// Saving changes automatically assigns a new Id to movie
      	db.SaveChanges();
      }
      
    2. Read - Read all movies
      var movieList = new List<Movie>();
      
      // Add all movies from database to movieList
      using (var db = new MovieTheaterContext())
      {                
      	foreach (var movie in db.Movies)
      	{
      		movieList.Add(movie);
      	}
      }  
      
    3. Update - Change an existing movie
      // Assume movie.Id is set to an existing database movie 
      movie.Title = "Tron Returns";
      movie.Rating = "PG";
      	
      using (var db = new MovieTheaterContext())
      {
      	db.Movies.Update(movie);
      	db.SaveChanges();
      }
      
    4. Delete - Delete an existing movie
      // Assume movie.Id is set to an existing database movie 
      using (var db = new MovieTheaterContext())
      {
      	db.Movies.Remove(movie);
      	db.SaveChanges();
      }
      
  6. Viewing database data
    1. Run the app and add some movies
    2. theater.db is created in C:\Users\USERNAME\AppData\Local\Packages\KEY\LocalState
    3. DB Browser for SQLite can examine and modify the contents of a .db file
    4. Open theater.db in DB Browser for SQLite to see Movies table

      Screenshot of DB Browser for SQLite showing Movies table with columns Id, Title, Rating.
    5. Browse data - Id column is auto-incremented

      Screenshot of DB Browser for SQLite showing Movies table with rows '1, Tron, PG', '2, Braveheart, R', '3, Princess Bride', PG'.