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

标签 c# linq

我有两个表,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/

相关文章:

c# - 如何避免重复代码?

c# - LINQ to xml - 如何选择特定节点?

c# - 如何在没有循环的情况下用 100 个空 List<T> 填充 list<list<T>>?

c# - 根据 c# windows 中另一列的值对 datagrid 中的列值求和

c# - 模拟CloudStorageAccount和CloudTable for Azure表存储

c# - 如何订购列表<string>

c# - 正确使用 Marshal.Copy

c# - 逐个元素除法或乘法 - c# 与 f# 比较

sql - Linq to SQL nvarchar问题

c# - LINQ to SQL 加入 FirstOrDefault() 问题