简体   繁体   中英

How can I perform this query using L2E?

I have a 2 tables:

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. The relationship properties should be used instead.

checkout the answer by Craig Stuntz for a cleaner way if you have a relation defined

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

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