我有两个表,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 的一部分,但我想知道如何在一个查询中使用返回 bool 值的连接进行授权。
函数签名为:
public bool GetUserAuthorizedOnPeachID(int TheUserID, long ThePeachID)
谢谢。
最佳答案
根据您所拥有的使用以下架构:
你可以使用这个函数/查询:
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;
}
}
关于c# - 连接 2 个表的测试记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13941301/