需要帮助将SQL转换为EF4

时间:2010-12-23 05:11:26

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

我需要帮助将此SQL语句转换为EF4:

Select Posts.PostID, Post, Comment
from Posts left join
 Comments on posts.PostID = Comments.PostID
    Where CommentID not in 
    (
     Select PostID
     from Votes
     where VoteTypeID = 4 --4 = flagged comment type
    )

在我的数据库中,Votes表存储报告的帖子的PostID,或Votes.PostID列中报告的评论的CommentID

提前致谢!

2 个答案:

答案 0 :(得分:0)

如果没有看到您的模型,很难确定。但这应该让你开始。 如果您愿意,可以发布您的模型或EDMX的图片,我可以更好地看一下。

var myPosts = from p in posts
              where !p.Comments.Any(c => c.Votes.VoteID != 4)
                PostId = p.PostId,
                //other field needed here
              };

答案 1 :(得分:0)

using (var context = new Model1Container())
{
  var posts = context.Posts.
    All((p)=> p.Votes.All((v) => v.VoteTypeId!=4));

  //Or
  var posts2 = from p in context.Posts
          where p.Votes.All((v)=> v.VoteTypeId != 4)
          select p;                
}

更新:
根据我的理解,您想要所有帖子,但是对于每个帖子,您想要过滤其评论,如果是这种情况,您可以使用ToDictionary

var posts =
  context.Posts.
  //Include("Comments").
    ToDictionary(
      (p) => p, 
      (p) => p.Comments.Where((c)=> c.Votes.All((v) => v.VoteTypeId !=4))
    );

foreach (var item in posts)
{
  var post = item.Key;
  var comments = item.Value;
}

注意:如果禁用了延迟加载,则取消注释Include方法,并且您明确希望在此查询中急切加载注释。

UPDATE2:

var postsCollection = posts.Keys.ToArray();
var commentsCollection = posts.Values.ToArray();