2012-12-18 39 views
2

我有兩個表,FruitInventoryPeachInventory,他們有以下幾列:測試記錄與加入2個表

FruitInventory 
FruitID | UserID | .... 

PeachInventory 
PeachID | FruitID | ... 

我想測試,如果用戶是基於是否授權訪問一定PeachID或者他沒有經過PeachID的FruitID授權。

爲了測試,如果他授權的FruitID,我正在做這樣的事情:

public bool GetUserAuthorizedOnFruitID(int TheUserID, long TheFruitID) 
{ 
    using (MyDataContext TheDC = new MyDataContext()) 
    { 
     bool IsAuthorized = false; 

     IsAuthorized = TheDC.FruitInventory 
          .Any(f => f.FruitID == TheFruitID && 
            f.UserID == TheUserID); 

     return IsAuthorized; 
    } 
} 

我知道我能做到這一點會變成這樣一個後執行第二查詢,並會檢查是否ThePeachID是是TheFruitID的一部分,但我想知道如何使用返回布爾值的連接在一個查詢中執行授權。

函數簽名是:

public bool GetUserAuthorizedOnPeachID(int TheUserID, long ThePeachID) 

感謝。

回答

2

使用下面的架構基礎上,你有什麼:

enter image description here

您可以使用此功能/查詢:

public bool GetUserAuthorizedOnPeachId(int userid, int peachId) 
{ 
    using(var context = new MyDataDataContext()) 
    { 
     bool isAuthorized = false; 
     isAuthorized = (from p in context.PeachInventories.Where(p => p.PeachId == peachId) 
                                    join f in context.FruitInventories.Where(f => f.UserId == userid) on p.FruitId equals f.FruitId select p).Any(); 

     return isAuthorized; 

    } 
} 

您也可以使用鏈中的LINQ這樣:

public bool GetUserAuthorizedOnPeachIdUsingAChainQuery(int userid, int peachId) 
{ 
    using (var context = new MyDataDataContext()) 
    { 
     bool isAuthorized = false; 

     isAuthorized = context.PeachInventories.Where(p => p.PeachId == peachId) 
         .Join(context.FruitInventories.Where(f => f.UserId == userid), p => p.FruitId, f => f.FruitId, (p, f) => f).Any(); 

     return isAuthorized; 

    } 
} 
+0

事實上,我正在尋找測試PeachID,因此函數是公共BOOL GetUserAuthorizedOnFruitId(INT用戶ID,INT peachId),而不是(INT用戶ID,INT fruitId) – frenchie

+0

更新使用PeachId與FruitId和切換查詢周圍。 – CodeLikeBeaker

+0

好吧,酷,現在我認爲它的工作;謝謝。我把它降低了,因爲它根本不是正確的查詢,但我剛剛提出,因爲現在它是正確的。 – frenchie

1

從內存中這樣做:

IsAuthorized = (from f in TheDC.FruitInventory 
       join p in TheDC.PeachInventory on p.FruitID equals f.FruitID 
       where f.UserID == TheUserID 
        && p.PeachID == ThePeachID 
       select p.PeachID).Any() 

如果用戶有通過加入對水果標識水果庫存訪問給定桃花這將檢查。

1

這是鏈式LINQ查詢的解決方案。

bool exists = TheDC.PeachInventory.Join(TheDC.PeachInventory, 
          peach=> peach.FruitID, 
          fruit=> fruit.FruitID, 
          (peach, fruit) => fruit).Any(f => f.FruitID == TheFruitID &&               
                  f.UserID == TheUserID)