0

Let say I have the following tables:

Category: ID, Name, Limit
News: ID, Title
Relation: CID, NID

I want to select top 'x' news from News table with CID, CName and that 'x' depends on Category.Limit. For e.g

Category

ID        Name         Limit
1         A            2
2         B            3

News

ID        Title
1         News 1
2         News 2
3         News 3
4         News 4

Relation

CID       NID
1         1
1         2
1         3
2         4
2         3
2         2
2         1

Then we will have the result:

CID          CName        NID          NTitle

1            A            1            News 1
1            A            2            News 2
2            B            4            News 4
2            B            3            News 3
2            B            2            News 2

Is it possible to achieve the result with only 1 linq query? If not then a store procedure?

Any helps would be appreciated!

4

1 回答 1

0

如果我理解正确,对于每个类别,您都希望获得第一条x新闻,x该类别的限制在哪里。

var result = context.Categories
                    .SelectMany(c => c.News
                                      .Take(c.Limit)
                                      .Select(n => new
                                                   {
                                                       CID = c.CID, 
                                                       CName = c.CName,
                                                       NID = n.NID,
                                                       NTitle = n.NTitle
                                                   }));

此答案假定Category实体包含一个导航属性News,该属性包含属于某个类别的所有新闻。

于 2011-06-21T09:28:45.450 回答