-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEF Core 共變查詢(TPH 繼承映射).linq
More file actions
64 lines (55 loc) · 1.61 KB
/
EF Core 共變查詢(TPH 繼承映射).linq
File metadata and controls
64 lines (55 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<Query Kind="Program">
<NuGetReference>Microsoft.EntityFrameworkCore</NuGetReference>
<NuGetReference>Microsoft.EntityFrameworkCore.InMemory</NuGetReference>
<Namespace>Microsoft.EntityFrameworkCore</Namespace>
</Query>
// 1️⃣ 定義基底與衍生類別
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Employee : Person
{
public string Department { get; set; }
}
// 2️⃣ 建立 DbContext
public class MyAppContext : DbContext
{
public DbSet<Person> People { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// 使用本地 SQLite 測試資料庫
optionsBuilder.UseInMemoryDatabase("TestDb");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// 預設是 TPH (Table-Per-Hierarchy) 模式
// EF Core 會自動建立 Discriminator 欄位
modelBuilder.Entity<Person>()
.HasDiscriminator<string>("PersonType")
.HasValue<Person>("Person")
.HasValue<Employee>("Employee");
}
}
// 3️⃣ 測試程式
class Program
{
static void Main()
{
using var context = new MyAppContext();
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
// 新增一些資料
context.People.AddRange(new Person { Name = "Ray" },
new Employee { Name = "Emma", Department = "IT" });
context.SaveChanges();
// 共變查詢:從 Person DbSet 取出 Employee
var employees = context.People.OfType<Employee>().ToList();
Console.WriteLine("Employees:");
foreach (var e in employees)
{
Console.WriteLine($"Name: {e.Name}, Department: {e.Department}");
}
}
}