0

我有一组使用外键链接的表,如下所示

A 1----* B 

也就是说,A 可以有许多 B 记录。

如果将某个标志传递给我的函数,我需要添加一个“where”子句来返回 B.isMax == true 的所有 A 记录。我不知道如何处理这个。

public List<A> GetA(int AID, string AName, bool? isActive, bool? isMax)
    {
        var q = from a in Context.A
                select a;

        if (AID > 0)
        {
            q = q.Where(c => c.AID == AID);
        }

        if (!string.IsNullOrEmpty(AName))
        {
            q = q.Where(c => c.Name.Contains(AName));
        }

        if (isActive != null)
        {
            q = q.Where(c => c.IsActive == isActive);
        }

        if (isMax != null)
        {
            // ???? Can't do this. How can I implement this kind of thing??
            q = q.Where(c => c.B.IsMax == isMax);
        }

        List<A> ret = q.ToList();

        return ret;
    }

有什么想法吗??

4

3 回答 3

2

您可以使用Any

q = q.Where(c => c.B.Any(i => i.IsMax == isMax));

Any用于检查序列的任何元素是否满足条件

于 2013-03-01T17:32:57.697 回答
1

你的意思是Any

q = q.Where(c => c.B.Any(b => b.IsMax == isMax));
于 2013-03-01T17:33:33.653 回答
0

你觉得,做这样的事情是个好主意吗?

public List<A> GetA(int AID, string AName, bool? isActive, bool? isMax)
{
    return Context.A
            .Where(c =>
                       (AID <= 0 || c.AID == AID)
                    && (string.IsNullOrEmpty(AName) || c.Name.Contains(AName))
                    && (isActive == null || c.IsActive == isActive)
                    && (isMax == null || c.B.Any(b => IsMax == isMax))
                  )
            .ToList();
}
于 2013-03-01T17:48:06.857 回答