ASP.NET Core:获取外键时的NullReferenceException

问题描述 投票:3回答:1

我正在为电脑俱乐部预订系统。

当我尝试获取实例的外键时,我正在获取NullReferenceException

例:

var queue = _db.Queues.First(q => q.Index == 1);
Console.WriteLine(queue.QueueId); // works fine (primary key)
Console.WriteLine(queue.Index); // works fine (simple property)
Console.WriteLine(queue.User.Id); // NullReferenceException (foreign key)

显然,queue本身不是空的,但是queue.User是空的。怎么可能?

entity-framework foreign-keys nullreferenceexception asp.net-core-identity
1个回答
0
投票

尝试在EF核心查询中使用Include。请参阅Loading related data

using Microsoft.EntityFrameworkCore;

var queue =_db.Queues.Include(q => q.User).First(q => q.Index == 1);
© www.soinside.com 2019 - 2024. All rights reserved.