2015-04-12 74 views
0

我是LINQ to SQL的初學者。我正在嘗試在LINQ中使用SQL IN運算符的子查詢。 我試圖整合查詢friends_Afriends_B與SQL子查詢運營商在帖子查詢:LINQ to SQL,與IN運算符一起使用子查詢

where p.UserName IN (friends_A)
where p.UserName IN (friends_B)

我不在乎是否將整合子查詢內聯或使用變量。

的問題是:
如何使用SQL IN操作符的查詢friends_Afriends_B(inline或使用變量)集成?

額外的問題: orderby p.DateAndTime:如何從工會責令整個結果(var posts)?

using (FacebookDataEntities entities = new FacebookDataEntities()) 
{ 

    var friends_A = from f in entities.Friends 
        where f.Friend_A != User.Identity.Name 
        && f.Friend_B == User.Identity.Name 
        select f.Friend_A; 

    var friends_B = from f in entities.Friends 
        where f.Friend_A == User.Identity.Name 
        && f.Friend_B != User.Identity.Name 
        select f.Friend_B; 

    var posts = ((from p in entities.Posts 
    where p.UserName.ToLower() == User.Identity.Name 
    select new { p.UserName, p.DateAndTime, p.PostText }) 

    .Union(from p in entities.Posts 
      where p.UserName IN (friends_A) 
      select new { p.UserName, p.DateAndTime, p.PostText }) 

    .Union(from p in entities.Posts 
      where p.UserName IN (friends_B) 
      select new { p.UserName, p.DateAndTime, p.PostText })); 

    ListViewPosts.DataSource = posts.ToList(); 
    ListViewPosts.DataBind(); 
} 

回答

1

看着你的代碼,我認爲這是你需要的。通過這樣做,你也可以避免工會。

var friends_A = from f in entities.Friends 
        where f.Friend_A != User.Identity.Name 
        && f.Friend_B == User.Identity.Name 
        select f.Friend_A; 

var friends_B = from f in entities.Friends 
        where f.Friend_A == User.Identity.Name 
        && f.Friend_B != User.Identity.Name 
        select f.Friend_B; 

var posts = 
    from p in entities.Posts 
    let userName = p.UserName.ToLower() 
    where 
     userName == User.Identity.Name || 
     friends_A.Concat(friends_B).Contains(userName) 
    orderby 
     p.DateAndTime 
    select new 
    { 
     p.UserName, 
     p.DateAndTime, 
     p.PostText 
    }; 
0

你可以試試這個。

.Union(from p in entities.Posts 
     where friends_A.Any(f => f.Name == p.UserName) 
     select new { p.UserName, p.DateAndTime, p.PostText }) 

.Union(from p in entities.Posts 
     where friends_B.Any(f => f.Name == p.UserName) 
     select new { p.UserName, p.DateAndTime, p.PostText }));