据我所知,它们都带来了嵌套实体,或者我应该说分层数据。 IE。客户以及每个客户的订单。此外,它们都呈现为数据库级别的连接 - 内部或左侧,具体取决于外键设置。我猜 EF 正在使它们从平面嵌套。
通过投影查询,我们可以精确选择嵌套实体的外部和内部级别所需的列。据我所知,使用“包含”我们无法选择特定的列。我不确定加入群组的情况如何?
我说得对吗?你还能说什么?谢谢你。
我进行了研究,但没有发现在这件事上提出的问题。
你是对的,如果你使用
virtual ICollection<...>
属性,实体框架会将它们转换为 GroupJoin
要检查这一点,您可以检查创建的 SQL 代码
void LogText(string text)
{
// in this example write text to the debug screen:
System.Diagnostics.Debug.WriteLine(text);
// of course you could decide to append to a file, or log in a database
}
记录生成的sqlText示例:
ICollection<Book> GetBooksOfAuthor(string authorName)
{
using (var dbContext = new MyLibraryDbContext(...))
{
// make sure that the generated Sql text is logged:
dbContext.Database.Log = generatedSqlText => LogGeneratedSqlText(generatedSqlText);
IQueryable<int> authorIds = dbContext.Authors
.Where(author => author.Name == authorName)
.Select(author => author.Id);
IQueryable<book> booksOfAuthorsWithName = dbContext.Books
.Where(book => authorIds.Contains(book.AuthorId);
// note: the query is not executed yet!
// execute the query. The generated sql text is logged:
return booksOfAuthorsWithName.ToList();
}
}
您可以将所有内容放在一个大的 LINQ 语句中。由于只有执行ToList后才会执行查询,因此这不会提高效率。然而,它会降低可读性和可测试性。
有些人不喜欢使用
virtual ICollection<...>
属性。当然,您可以使用(组)连接来代替,甚至可读性更差!