本实验演示基于上个实验构建的模型类,通过 EF Core 对数据进行 CRUD。
任务
展示各个 Actor 的所有 Film
DbSet
类可以通过 InClude 和 ThenInclude 方法加载相关数据 Film 与 Actor 的关系是多对多,FilmActor 就是多对多关系表
在数据库里面新增一个 City
Context 类有 Add 方法
操作完记得 SaveChanges
更新你刚才添加的 City
- Update 方法
删除你刚才添加的 City
- Delete 方法
注:在尝试运行下面的代码前,在 VS Code 中执行全文替换(Ctrl + Shift + H),将所有 sbyte 替换为 byte。
Task1:读取多表连接的数据
通过 Include 和 ThenInclude 将 Film、FilmActor 和 Actor 表连接起来,再读取数据。
using System;
using MyApp.Models;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace MyApp
{
class Program
{
static void Main(string[] args)
{
var dbContext = new sakilaContext();
var records = dbContext.Film.Include(f => f.FilmActor).ThenInclude(r => r.Actor).ToList();
foreach (var record in records)
{
System.Console.WriteLine($"Film: {record.Title}");
var counter = 1;
foreach (var fa in record.FilmActor)
{
System.Console.WriteLine($"\t Actor {counter++}: {fa.Actor.FirstName} {fa.Actor.LastName}");
}
}
}
}
}
输出如下:
Film: ACADEMY DINOSAUR
Actor 1: WARREN NOLTE
Actor 2: MENA TEMPLE
Actor 3: OPRAH KILMER
Actor 4: ROCK DUKAKIS
Actor 5: CHRISTIAN GABLE
Actor 6: JOHNNY CAGE
Actor 7: PENELOPE GUINESS
Actor 8: SANDRA PECK
Actor 9: MARY KEITEL
Actor 10: LUCILLE TRACY
...
Film: ZORRO ARK
Actor 1: LISA MONROE
Actor 2: IAN TANDY
Actor 3: NICK DEGENERES
Task2:插入数据
var dbContext = new sakilaContext();
var city = new City() { CityId = 1001, Name = "Wonderland", CountryId = 109 };
dbContext.Add(city);
dbContext.SaveChanges();
注:
你需要将 City 类自动生成的 City1 属性重命名为 Name
虽然 city_id 列是自增的,你在插入 city 时也必须手动指定唯一的 ID
执行代码后,打开 MySQL Workbench 用 SELECT * FROM city WHERE city_id = 1001
去查看插入的 city。
Task3:更新数据
var uTarget = dbContext.City.SingleOrDefault(c => c.CityId == 1001);
if (uTarget != null)
{
uTarget.Name = "Kirkland";
dbContext.Update(uTarget);
dbContext.SaveChanges();
}
Task4:删除数据
var uTarget = dbContext.City.SingleOrDefault(c => c.CityId == 1001);
if (uTarget != null)
{
dbContext.Remove(uTarget);
dbContext.SaveChanges();
}