简体   繁体   English

如何使用L2E执行此查询?

[英]How can I perform this query using L2E?

I have a 2 tables: 我有2张桌子:

Activities       ActivityKeywords
**********       ****************
ID         -->   ActivityID
Name             Keyword

I need to return all activities that match a specific keyword. 我需要返回与特定关键字匹配的所有活动。

var q = from a in Context.Activities
        where a.Keywords.Any(k => k.Keyword == someKeyword)
        select a;

As I said in comments, it's nearly always wrong to use join in LINQ to Entities. 正如我在评论中所说,在LINQ to Entities中使用join几乎总是错误的。 The relationship properties should be used instead. 应该使用关系属性代替。

checkout the answer by Craig Stuntz for a cleaner way if you have a relation defined 如果定义了关系,请查看Craig Stuntz的答案以更简洁的方式

My previous response was wrong but this works for me. 我之前的回答是错误的,但这对我有用。

var activities = from a in db.Activities 
                 join ak in db.ActivityKeywords on a.ID equals ak.ActivityID 
                 where ak.Keyword == "yourkeyword" 
                 select a;

I think you need something like 我想你需要像

Give me all Activities which ID are in a list of ActivitiyKeywords.ID's

If that is your question, the you can try this: 如果这是您的问题,则可以尝试以下操作:

var ids = from k in db.ActivityKeywords select k.ActivityID;

var result = from a in db.Activities where ids.Contains(a.ID) select a;

More information here . 更多信息在这里

var results = (from a in Activities
               from k in ActivityKeywords
               where k.Keyword == "keyword" && k.ActivityID == a.ID
               select a).Distinct();

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

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