简体   繁体   English

在效率更高的Linq中,加入或包含

[英]In Linq, which is more efficient, join or include

I'm trying to get a collection of objects, and I would like to find out which is more efficient. 我正在尝试收集对象的集合,并且我想找出哪个更有效。 Right now my query gets 16 results, but we may be working with a dataset of 1000s. 现在,我的查询有16个结果,但我们可能正在使用1000s的数据集。

Let's say I'm working with the following models: 假设我正在使用以下模型:

public ProjectSubmission()
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public Guid ProjectSubmissionId { get; set; }

    public System.Guid ProjectId { get; set; }
    [ForeignKey("ProjectId")]
    public virtual Project Project { get; set; }

    public string SubmissionTitle { get; set; }  
}

public Project()
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public Guid ProjectId { get; set; }

    public string Title { get; set; } 
}

Which will provide me better performance, this: 这将为我提供更好的性能,这是:

var subVModel = 
(
    from ps in db.ProjectSubmission
        .Include(s => s.Project)
    where ps.IsActive
        && (filter.ProjectId == Guid.Empty || ps.Project.ProjectId == filter.ProjectId)
        && (filter.SubmissionTitle == string.Empty || ps.SubmissionTitle .Contains(filter.SubmissionTitle))
    select ps); 

or: 要么:

var subVModel = 
(
    from ps in db.ProjectSubmission
    join p in db.Project on ps.ProjectId equals p.ProjectId
    where ps.IsActive
        && (filter.ProjectId == Guid.Empty || p.ProjectId == filter.ProjectId)
        && (filter.SubmissionTitle == string.Empty || ps.SubmissionTitle .Contains(filter.SubmissionTitle))
    select ps); 

Right now they both result in .032 seconds for 16 records. 现在,它们都为16条记录产生了.032秒。

There will be no difference is simple case because the Include call generates a join clause to get the data from the included property. 简单情况不会有任何区别,因为Include调用会生成一个join子句以从includeed属性获取数据。 On the other hand if you want to select only some of the columns from the included navigation property you will not be able to do it with Include. 另一方面,如果您只想从包含的导航属性中选择某些列,则将无法使用“包含”来做到这一点。 If you use join you can specify which columns you want to include in the result set. 如果使用联接,则可以指定要包括在结果集中的列。

Although include is more simpler syntax to read , There is no difference in simple cases . 尽管include是更易于阅读的语法,但在简单情况下没有区别。 But in some cases include cause extra joins(Before EF 6.1). 但是在某些情况下,包括引起额外的联接(在EF 6.1之前)。 and cause extra time . 并造成额外的时间。 It's a bug in EF and reported here 这是EF中的错误,请在此处报告

Any way it's better to use a EF profiler and monitor your query . 无论如何,最好使用EF分析器并监视您的查询。 Like Entity Framework Profiler , or use Glimpse EF extension Entity Framework Profiler一样 ,或使用Glimpse EF扩展

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM