【问题标题】:Efficient join in Entity Framework/LINQ实体框架/LINQ 中的高效连接
【发布时间】:2015-12-08 17:53:42
【问题描述】:

我有两个 SQL Server 表,“名词”和“形容词”。对于每个名词,都有多个形容词。例如:{ 名词 = 苹果,形容词 = [水果,红色,甜]},{ 名词 = 球,形容词 = [红色,硬]}。每个名词大约有 5 个形容词。 Adjectives 表具有对 Nouns 表中 Id 字段的外键引用。我想要支持的查询是获取满足某个属性的所有名词(例如:获取在特定时间创建的所有名词)并满足形容词。一个示例查询是:Get me all of the nouns created at 7.30 AM today.

我的 LINQ 查询如下所示:

var currentTime = DateTime.Now;
var type = "Red";
return (from n in this.dbContext.Nouns where
                n.CreatedAt == currentTime && n.Adjectives.Any(a => a.AdjectiveType == type)
                orderby n.PriorityScore descending
            select new NounAdjectives
            {
                Term = n.Term,
                Adjectives = n.Adjectives
            }).Take(10).ToList();

此查询每次都会超时。我该如何改进?

【问题讨论】:

  • 我认为这会很快执行。
  • 不幸的是,它没有。 LINQ 生成的查询非常可怕。下面的答案执行起来相当快。
  • 嗯,我必须同意@RobertMcKee。如果您在第二个查询中像在原始查询中一样包含名词形容词会发生什么?
  • 在这种情况下工作正常。

标签: c# sql sql-server entity-framework linq


【解决方案1】:

我不确定您是否要获取名词符合该标准的每个形容词-名词组合,而是要获取所有符合该条件的名词

from n in this.dbContext.Nouns join adj this.dbContext.Adjectives on (insert FK and PK) where n.Created == currentTime AND adj.Name == "Red" Select n

【讨论】:

    猜你喜欢
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    相关资源
    最近更新 更多