Linq和EF on .Any()

时间:2011-03-15 07:56:37

标签: c# linq entity-framework linq-to-entities

我使用c#,linq和EF4。

我的概念模型中的数据库中有两个表:

数据库表:

CmsContents
CmsCategories
CmsRelatedCategories (Pure Juction Table)

实体类型:

CmsContent
CmsCategory

Entyt Set:

CmsContents
CmsCategories

我有一些导航属性:

for CmsContents --> CmsCategories --> Return Collection of Cms CmsCategory
for CmsCategories --> CmsContents --> Return Collection of Cms CmsContents

接口表的DataBase中的数据如下:

CategoryId     ContentId
7              1
7              2
9              2

我需要查询Entity Framwork来检索包含在连接表中的所有CmsContents。

目前我使用此代码:

var contents = from cnt in context.CmsContents
                               where cnt.CmsCategories.Any()
                               select cnt;

返回:

CmsContents
1
2

我需要显示结果:

CmsContents
1
2
2

我怀疑Any()只显示DISTINCT值,但我需要列出所有值。

知道怎么解决吗?。

你能不能给我写LINQ查询,这样我就可以得到清晰的图片。

1 个答案:

答案 0 :(得分:7)

Any()根本不返回值 - 它会返回 Boolean 值,以确定集合中是否有任何值。它只显示两个值,因为您只查询CmsContents,它有两行,并且两行至少有一个类别,因此两行都在结果中。

看起来你真的喜欢这样的事情:

var contents = from cnt in context.CmsContents
               from category in cnt.CmsCategories
               select cnt;
相关问题