2012-12-18 40 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)