开发者

Need help converting SQL to EF4 please

开发者 https://www.devze.com 2023-02-01 02:20 出处:网络
I need help converting this SQL statement, into EF4: Select Posts.PostID, Post, 开发者_StackOverflowComment

I need help converting this SQL statement, into EF4:

Select Posts.PostID, Post, 开发者_StackOverflowComment
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
    )

In my database, the Votes table stores either the PostID of reported posts, or CommentID of reported comments in the column Votes.PostID

Thanks in advance!


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;                
}

Update:
Based on my understanding you want all the posts, but for each post, you want to filter its comments, if that's the case, you could use 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;
}

Note: uncomment the Include method if lazy-loading is disabled, and you explicitly want to eager-load the comments in this query.

Update2:

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


This is hard to determine without seeing your Model. But this should get you started. If you would like you can post a picture of your model or the EDMX and I can take a better look at this.

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

精彩评论

暂无评论...
验证码 换一张
取 消