我开始学习 Entity Framework Core 和相应的 LINQ。但我遇到了这个问题:我有 2 个表:Table带有 fieldsId和(这是下一个表的外键),以及Name带有fields和.CategoryIdCategoryIdName
使用 LINQ 查询语法时,查询被正确处理,返回所需的数据。使用 LINQ 方法语法时,不返回任何内容。我在这段代码中犯了什么错误?
//Select objects that have "Breakfast" category + LINQ Method Syntax
Category category = context.Category.FirstOrDefault(c => c.Name == "Breakfast");
List<Table> tables = category.Table.ToList();
tables.ForEach(r => Console.WriteLine(r.Name)); //Returns nothing (tables.Count == 0) - ERROR
//Select objects that have "Breakfast" category + LINQ Query Syntax
var tablesQuery = (from t in context.Table
where t.Category.Name == "Breakfast"
select t).ToList();
tablesQuery.ForEach(t => Console.WriteLine((t as Table).Name)); //Returns proper data (tables.Count == 2) - CORRECT
您的问题是,当您加载 Categories 时,您认为关联的表加载了 categories
category.Table,但事实并非如此。您需要明确地说,亲爱的 EFCore,当您从数据库中提取类别时,请获取关联的category.Table. 要指定这一点,有一个特殊的方法Include,例如这里你看,我先是转到分类,然后立即要求拉起桌子
.Include(x=>x.Table),然后我已经做出了选择。但一般来说,当你需要从数据库中获取一张表时,你会更容易立即像这样查询它
在这里,您甚至不需要将类别加载到内存中。