-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAccessingADerivedDbSetPropertyUsingAbaseDbContext.linq
More file actions
54 lines (43 loc) · 1.51 KB
/
AccessingADerivedDbSetPropertyUsingAbaseDbContext.linq
File metadata and controls
54 lines (43 loc) · 1.51 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
<Query Kind="Statements">
<NuGetReference>Microsoft.EntityFrameworkCore</NuGetReference>
<NuGetReference>Microsoft.EntityFrameworkCore.InMemory</NuGetReference>
<Namespace>Microsoft.EntityFrameworkCore</Namespace>
</Query>
// ---- 測試 ----
using BaseContext ctx = new AppContext();
ctx.Add(new Person { Name = "Ray" });
ctx.Add(new Employee { Name = "Emma", Department = "IT" });
ctx.SaveChanges();
BaseContext baseCtx = ctx;
// ✅ 以基底參考拿衍生實體(不用轉型)
var e1 = baseCtx.Set<Employee>().ToList();
e1.Dump();
// ✅ 共變查詢
var e2 = baseCtx.Set<Person>().OfType<Employee>().ToList();
e2.Dump();
// ❌ 看不到衍生屬性
// baseCtx.Employees // 編譯錯誤
// ✅ 需要屬性才轉型
var e3 = (ctx as AppContext).Employees.ToList();
e3.Dump();
public class Person { public int Id { get; set; } public string Name { get; set; } }
public class Employee : Person { public string Department { get; set; } }
public abstract class BaseContext : DbContext
{
public DbSet<Person> People { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder b)
=> b.UseInMemoryDatabase("demo");
protected override void OnModelCreating(ModelBuilder m)
{
m.Entity<Person>()
.HasDiscriminator<string>("Discriminator")
.HasValue<Person>("Person")
.HasValue<Employee>("Employee");
// 確保 Employee 被模型認得(若沒有 DbSet<Employee> 也沒關係)
m.Entity<Employee>();
}
}
public class AppContext : BaseContext
{
public DbSet<Employee> Employees { get; set; }
}