gpt4 book ai didi

c# - 连接 2 个表的测试记录

转载 作者:行者123 更新时间:2023-11-30 21:01:42 25 4
gpt4 key购买 nike

我有两个表,FruitInventoryPeachInventory,它们有以下列:

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)

谢谢。

最佳答案

根据您所拥有的使用以下架构:

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;

}
}

关于c# - 连接 2 个表的测试记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13941301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com