我是否可以使用“包含”优化单个linq查询到预先加载的查询元素

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

我有一个c#类PersonNote,它们映射到Sql Server表并与Entity Framework一起使用。在Person数据模型中,Note是延迟加载的:

public class Person {
    public int PersonId { get; set; }
    public int PersonType { get; set; }

    public int? NoteId { get; set; }
    public virtual Note Note { get; set; }
}

当我使用linq查询时,在查询开头显式使用Include是否有任何优势?这是这样的:

personCount = myContext.Person.Include(p => p.Note).Count(
    m => m.PersonType == 3 &&
    (m.Note.Expires == null || m.Note.Expires > DateTime.Now))

比这更有效:

personCount = myContext.Person.Count(
    m => m.PersonType == 3 &&
    (m.Note.Expires == null || m.Note.Expires > DateTime.Now))
c# entity-framework linq
1个回答
1
投票

在这种情况下,使用Include没有任何好处。

Include用于确保关联的链接实体类型被急切加载(而不是默认的延迟加载)。这避免了大量请求加载每个引用的实例(例如,在迭代集合时)。

但是你没有在这里返回任何实体类型。因此,急切或懒惰的加载是无关紧要的。

© www.soinside.com 2019 - 2024. All rights reserved.