DbContext instance represents a database session and is
used to query and save entity instances
OnConfiguring() to configures the database.
DbContextOptionsBuilder carries configuration information for DbContext and provides
methods to select a database like UseSqlServer() or UseSqlite()
Add(), Update(), Remove() and can be treated as
a collection to loop through all rows in the associated table
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");
}
}
}
Movie class to Models folder
INotifyPropertyChanged to support UI data binding
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; }
}
}
DbContext to ensure correct use of IDisposable objects
// 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();
}
}
...
}
}
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();
}
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);
}
}
// 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();
}
// Assume movie.Id is set to an existing database movie
using (var db = new MovieTheaterContext())
{
db.Movies.Remove(movie);
db.SaveChanges();
}