2010-08-29 102 views
0

我有一個項目的簡單評級應用程序。主要有三個表:LINQ聯盟列如果驗證

Item 
{ 
    ItemID, 
    Contents 
} 

asp_User 
{ 
    UserID, 
    Name 
} 

Rating 
{ 
    RatingID, 
    ItemID, 
    UserID, 
    int Rating 
} 

我有LINQ代碼讀取項目:

var q = from item db.Item 
     select item; 

那麼我想追加到包含評級的當前認證的每個項目行QA列用戶。如果用戶未登錄或沒有經過認證的用戶提供評級,結果將爲0.

如果有問題,我正在使用SqlMembershipProvider。

Q的最終結果應該是這個樣子:

[認證]

//The currently authenticated user has commented on Item.ID = 1 and has given it a 9. 
q = {ID = 1, Contents = "Whatever", Rating = 9}, 

//The currently Authenticated user has not commented on Item.ID = 2. 
{ID = 2, Contents = "Something", Rating = 0}; 

[未通過身份驗證]

//There is not an authenticated user 
q = {ID = 1, Contents = "Whatever", Rating = 0}, 

//There is not an authenticated user 
{ID = 2, Contents = "Something", Rating = 0}; 

回答

0

你有什麼打算用「var q」做什麼?很難說出你的意圖是什麼,在這種情況下,這很重要。這裏是我能做的最好的基礎上缺乏的上下文。希望這將有助於:

if(User.IsAuthenticated) 
{ 
    var q = from item in db.Item 
      join r in db.Rating on c.Id equals r.ItemId 
      select new {ID = item.Id, Contents = item.Contents, Rating = r.Rating}; 

    // Do whatever you want with this here. 
} 
else 
{ 
    var y = db.Item; 

    // Do whatever you want with this here. 
} 
0

從性能角度來看,Ocelots解決方案是要走的路(特別是如果您查詢多個項目)。

public partial class Item 
{ 
    public int Rating 
    { 
     get 
     { 
      if (!Thread.CurrentPrincipal.Identity.IsAuthenticated) 
       return 0; 

      using (var db = new ApplicationDataContext()) 
      { 
       return db.Item 
        .Where(r => r.ItemID == this.ItemID 
         && r.UserID == Thread.CurrentPrincipal.Identity.Name) 
        .Select(r => r.Rating) 
        .SingleOrDefault(); 
      } 
     } 
    } 
} 

如果你想: 但是滿足這一評級應該是項目的屬性的情況下,你可以用你的LINQ到SQL數據類相同的命名空間內的部分類擴展Item類要獲得與Ocelot提出的單個SQL請求相同的結果,您應該使用GroupJoin(像SQL LEFT OUTER JOIN一樣工作),然後像上面那樣選擇當前用戶評級。