linq to sql返回布尔值 [英] linq to sql to returning boolean

查看:80
本文介绍了linq to sql返回布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表Fruits,其中包含以下列

I have a table Fruits that contains the following columns

UserID | FruitID

我想验证用户ID是否在FruitID上得到授权,所以我正在写如下代码:

I want to verify that the UserID is authorized on the FruitID so I'm writing something like this:

var IsAuthorized = (from f in MyDC.Fruits
                    where f.UserID == TheUserID && f.FruitID == TheFruitID
                    select f.FruitID).SingleOrDefault();

因此,如果用户被授权,则查询返回ID;如果用户未被授权,则返回null.然后,我检查返回值是否为null,然后根据返回值设置布尔值.

So if the user is authorized the query returns an ID and if he's not authorized, it returns null. I then check to see if the return value is null and then set a bool based on the returned value.

我想做的是返回布尔值:如果用户被授权,则应该返回true.

What I want to do is return bool: if the user is authorized then it should return true.

如何修改查询以返回布尔值?

How can I modify the query to return a boolean?

谢谢.

推荐答案

var IsAuthorized = from (f in MyDC.Fruits
                         where f.UserID == TheUserID && f.FruitID == TheFruitID
                         select f.FruitID).SingleOrDefault() != null;

或者如果您希望由底层的LINQ提供程序完成此操作(例如,如果您使用的是SQL Server),则可以使用

or if you want this to be done by the underlying LINQ provider (for example if you are using SQL server) you could use the .Any extension method which is better:

var IsAuthorized = MyDC
    .Fruits
    .Any(f => f.UserID == TheUserID && f.FruitID == TheFruitID);

这篇关于linq to sql返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆