我有这个架构:
...我想使用此查询选择一些记录:
SELECT
Articles.ArticleId,
Articles.Title,
Articles.Tooltip,
Articles.UriTitle,
Articles.SubTitle,
Articles.Published,
Tags.TagId
FROM Articles INNER JOIN
ArticleTag ON Articles.ArticleId = ArticleTag.ArticleId INNER JOIN
Tags ON ArticleTag.TagId = Tags.TagId
WHERE (Tags.TagId = @tagid) AND (Articles.Published = 1)
有人可以帮助我将此查询转换为EF 4.1 Code First(一个lambda表达式)吗?
更新
我使用@Ladislav Mrnka代码(作为lambda表达式)并且代码有效!现在我把生成的sql放在这里,并检查它以确保没有问题:
// C#:
var query = context.Articles.Where(a => a.Published && a.Tags.Any(t => t.TagId == tagId))
.Select(a = new {
a.ArticleId,
a.Title,
a.Tooltip,
a.UriTitle,
a.SubTitle,
a.Published
});
并且生成的sql是
SELECT
[Extent1].[ArticleId] AS [ArticleId],
[Extent1].[Title] AS [Title],
[Extent1].[Tooltip] AS [Tooltip],
[Extent1].[UriTitle] AS [UriTitle],
[Extent1].[SubTitle] AS [SubTitle],
[Extent1].[Description] AS [Description],
[Extent1].[Keywords] AS [Keywords],
[Extent1].[MetaDescription] AS [MetaDescription],
[Extent1].[CreatedAt] AS [CreatedAt],
[Extent1].[UpdatedAt] AS [UpdatedAt],
[Extent1].[Viewed] AS [Viewed],
[Extent1].[Published] AS [Published],
[Extent1].[Body] AS [Body]
FROM [dbo].[Articles] AS [Extent1]
WHERE ([Extent1].[Published] = 1) AND ( EXISTS (SELECT
1 AS [C1]
FROM [dbo].[ArticleTag] AS [Extent2]
WHERE ([Extent1].[ArticleId] = [Extent2].[ArticleId]) AND ([Extent2].[TagId] = @p__linq__0)
))
答案 0 :(得分:1)
尝试:
int tagId = ...;
var query = from a in context.Articles
where a.Tags.Any(t => t.TagId == tagId) && a.Published
select new
{
a.ArticleId,
a.Title,
a.Tooltip,
a.UriTitle,
a.SubTitle,
a.Published,
tagId // I'm not sure if this will work but let give it a try
};
如果选择TagId
不起作用,则问题不是太大,因为您知道所有记录都有相同的标记ID。