I'm new to EF and Linq.
I have 2 tables, a "News" table and a "Related news" table. Each News item has should show several Related News items.
"News" contains a unique Id and details of the news story.
Each row of "Related news" has a reference to the parent ID in the "News" table and a reference to an ID of a related news stories, which again corresponds to an ID in the "News" table
I'm trying to create a linq query that given a News ID, will show a list of related news stories, with details taken from the "News" table.
The best I've managed is the following, but this just takes stories from the news table based on the parent key, rather than the related news item key.
var query = from n in context.NewsPosts
from nr in n.RelatedNewsPosts
where nr.NewsId == NewsId
select n;
I have a feeling the correct query is probably not too complicated, but I can't figure it out!
Any help much appreciated!
You had the NewsPosts and RelatedNewsPosts tables switched. Given a news id, look at all the RelatedNewsPosts for that id, then join to the NewsPosts it refers to.
Not tested, but I think this is the idea of what you're looking for (not knowing exactly how it's set up, but at least you get the main idea):
var givenNewsId = ...;
var query = from nr in context.RelatedNewsPosts
join n in context.NewsPosts on nr.RelatedNewsId equals n.NewsId
where nr.NewsId = givenNewsId
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.