Entity Framework Core 数据操作全解析
1. 子对象更改跟踪
在 Entity Framework Core 中,更改跟踪机制同样适用于子对象。以下代码展示了如何加载 Flight
对象及其关联的 Pilot
对象,并对它们进行更改:
public static void ChangeFlightAndPilot()
{
CUI.MainHeadline(nameof(ChangeFlightAndPilot));
int flightNo = 101;
using (WWWingsContext ctx = new WWWingsContext())
{
var f = ctx.FlightSet.Include(x => x.Pilot).SingleOrDefault(x =>
x.FlightNo == flightNo);
Console.WriteLine($"After loading: Flight #{f.FlightNo}:
{f.Departure}->{f.Destination} has {f.FreeSeats} free seats!\nState
of the flight object: " + ctx.Entry(f).State + " / State of the
Pilot object: " + ctx.Entry(f.Pilot).State);
f.FreeSeats -= 2;
f.P