0

大家早。

我有以下方法用于尝试恢复布尔值:

public static bool GetShowCatSubProdStatus(string memberid, string username)
    {
        MyEnts showcatsubprodstatus = new MyEnts.PDC_VDSOREntities35();

        var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
                where p.MemberID == memberid && p.UserName == username
                select p.ShowCatSubProd;

        return r.Any();
    }

当我调用这个方法并调试它时,结果是正确的。但是,当我在页面加载中运行此方法时,虽然方法结果返回了正确的结果,但当我单步执行时,布尔值会发生变化!

 bool showcatsubprodstatus = MyEnts.GetShowCatSubProdStatus(_memberid, _username);

        if (showcatsubprodstatus != true)
        {
            panCatSubProd.Visible = false;
        }

有人可以解释这里发生了什么以及我如何解决这个难题吗?!

PS:为厚脸皮道歉。

编辑 - 对,将其缩小到变量。无论方法结果如何,它总是返回“真”?!?!

4

1 回答 1

0

这段代码返回一个IEnumerable<bool>

var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
        where p.MemberID == memberid && p.UserName == username
        select p.ShowCatSubProd;

通过调用,.Any()您是在询问 IEnumerable 中是否有任何项目。如果有你返回true;

这就是为什么你总能得到真实的回报,因为它总能找到一些东西。

解决方案
您要么调用 .SingleOrDefault() ,它返回唯一的元素(如果有的话),要么返回该类型的默认值。

var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
        where p.MemberID == memberid && p.UserName == username
        select p.ShowCatSubProd;
return r.SingleOrDefault(); //assuming p.ShowCatSubProd is a bool and not a Nullable<bool> else you need to adjust your return type or cast it to a boolean using .GetValueOrDefault().
于 2010-09-28T10:05:33.177 回答