我有两个表,FruitInventory
和PeachInventory
,它们包含以下列:
FruitInventory
FruitID | UserID | ....
PeachInventory
PeachID | FruitID | ...
我想测试用户是否有权根据他是否在PeachID的FruitID上获得授权来访问某个PeachID。
为了测试他是否在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)
感谢。
答案 0 :(得分:2)
根据您拥有的内容使用以下架构:
您可以使用此功能/查询:
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;
}
}
答案 1 :(得分: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()
这将检查用户是否可以通过加入水果ID上的水果库存来访问给定的桃子。
答案 2 :(得分:1)
这是in chain 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)