简体   繁体   中英

Efficient join in Entity Framework/LINQ

I have two SQL Server tables, 'Nouns' and 'Adjectives'. For every noun, there are multiple adjectives. Ex: { Noun = Apple, Adjective = [Fruit, Red, Sweet] }, { Noun = Ball, Adjective = [Red, Hard]}. There are about 5 adjectives per noun. The Adjectives table has a foreign key reference to the Id field on the Nouns table. The query I want to support is to fetch all nouns that satisfy a certain property (ex: get me all the nouns that were created at a particular time) and also satisfy an adjective. An example query would be: Get me all the nouns that were created at 7.30 AM today and have red colour in them.

My LINQ query looks as follows:

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();

This query ends up timing out every single time. How can I improve this?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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