2014-01-07 71 views
0

我有兩個表使用數組中的值來查詢數據庫。郵政表和關注表。發佈表具有用戶的所有帖子,並且關注表具有用戶跟隨的用戶列表。無法使用LINQ

郵政表

PostID UserID  Post 
1   2  TextOne 
2   1  TextTwo 
3   1  Text3 
4   2  Text4 

按照表

ID  Following  FollowedBy 
1  2     1 
2  3     1 

而且我有一個列表視圖。

<ItemTemplate >  
    Post: 
    <asp:Label ID="Label1" runat="server" Text='<%# Eval("Post") %>' /> 
    <br /> 
    UserID: 
    <asp:Label ID="Label2" runat="server" Text='<%# Eval("UserID") %>' /> 
    <br />   
</ItemTemplate> 

我想顯示用戶以及他關注的人的帖子。我寫了下面的代碼。

int UserId = Convert.ToInt32(Session["User"]); 
int[] OthersPosts = (from s in Data.Follow where s.FollowedBy == UserId) select s.Following1).ToArray(); 

foreach (int post in OthersPosts) 
{ 
    var DisplayPost = (from s in Data.Posts where s.UserID == post && s.UserID == UserId) select s).ToList(); 
    ListViewPostTable.DataSourceID = ""; 
    ListViewPostTable.DataSource = DisplayPost; 
    ListViewPostTable.DataBind(); 
} 

但是沒有數據顯示在ListView上?

我在DisplayPost變量檢查值的監視窗口,它說:Enumeration yielded no results

+0

什麼在OthersPosts陣列的返回值? –

+0

的用戶ID的人,隨後的的「用戶ID」 –

+0

我認爲你有正確的查詢可能是這樣的: VAR DisplayPost =(從s在Data.Posts其中s.PostID ==後&& s.UserID ==用戶ID )select s).ToList(); –

回答

2

的錯誤是在下面的謂詞:

s.UserID == post && s.UserID == UserId 

由於UserIDpost這是他所遵循的一個用戶總是不同的,這個謂詞總是返回false

你應該把它至少更改爲

s.UserID == post || s.UserID == UserId 

即您想要由用戶自己或他所關注的用戶之一查找帖子。

如果他跟隨多個用戶,仍然無法正常工作,因爲在foreach循環中,您將多次綁定數據到ListViewPostTable。當然,最後你只會看到最後的結果。

嘗試更換foreach循環是這樣的:

var DisplayPost = (
    from s in Data.Posts 
    where s.UserID == UserId || OthersPosts.Contains(s.UserID) 
    select s).ToList(); 
ListViewPostTable.DataSourceID = ""; 
ListViewPostTable.DataSource = DisplayPost; 
ListViewPostTable.DataBind(); 
+0

哇!它的工作原理非常感謝:) –

+0

+ 1使用'Contains',而不是'foreach'。 –

+0

@GeneliaD'Souza你可能希望從'where'子句中刪除's.UserID == UserId ||',因爲它也會加載Session [「User」]的帖子。我想,這不是你想要的。 –

0

更改您這樣的代碼。

int UserId = Convert.ToInt32(Session["User"]); 
int[] OthersPosts = (from s in Data.Follow where s.FollowedBy == UserId) select s.Following1).ToArray(); 

List<Posts> lstPosts = new List<Posts>(); 

foreach (int post in OthersPosts) 
{ 
    var displayPost = (from s in Data.Posts where s.UserID == post) select s).ToList(); 
    lstPosts.AddRange(displayPost); 
} 

ListViewPostTable.DataSourceID = ""; 
ListViewPostTable.DataSource = lstPosts; 
ListViewPostTable.DataBind(); 

您正在匹配s.UserID == post && s.UserID == UserId。這是錯誤的,因爲一個帖子不會屬於兩個用戶。

+0

以下和FollowedBy是在查詢「int [] OthersPosts =(從s中Data.Follow其中s.FollowedBy == UserId選擇s .Following1).ToArray();」我怎麼能加載人,我下面的數組'其他郵件'和搜索'PostId'?仍然不工作,我認爲這是錯的 –

+0

其他正在加載UserId的 –

+0

是的,它會加載'UserID's。在'foreach'循環中,你會得到他們的帖子。 –