无法将lambda表达式转换为委托类型 [英] Cannot convert lambda expression to delegate type

查看:1241
本文介绍了无法将lambda表达式转换为委托类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用实体模型从SQL数据库中获取第一个用户,该模型正在与已经存在的数据库进行通信,该数据库具有我正在寻找的用户的用户ID。出现此错误和第二个错误。





无法将lambda表达式转换为委托类型'System.Func< iomnientitylibrary.user,bool>'因为块中的某些返回类型不能隐式转换为委托返回类型



无法将类型'int'隐式转换为'bool'



I'm trying to grab the first user from a SQL database using Entity model that is talking to a already existing database that has a userID of the user I am looking for. This and a second error appear.


Cannot convert lambda expression to delegate type 'System.Func<iomnientitylibrary.user,bool>' because some of the return types in the block are not implicitly convertible to the delegate return type

Cannot implicitly convert type 'int' to 'bool'

public user GetUser(int userID)
        {
            using (var context = new iomniEntities())
            {
                user u = context.users.FirstOrDefault(user => user.userID);

                return u;
            }
        }





context.users.ToList()工作正常,但我不想是 效率低下。

推荐答案

你的lambda错了,它需要返回一个布尔值而你的只是返回.userID。



您需要使用某种比较,例如:



user => user.userID == 10



FirstOrDefault返回与lambda表达式匹配的第一个或默认值(在您的情况下为null)。它不会返回列表中的第一个项目,这是我认为您想要的。不知道context.Users数据类型是什么,我不能告诉你更好的方法。



你可以使用类似的东西:



user => user!= null



但这不是最好的方法。
Your lambda is wrong, it needs to return a boolean and yours just returns the .userID.

You need to use some kind of comparison, like:

user => user.userID == 10

FirstOrDefault returns the first or default (null in your case) of the items that match the lambda expression. It does not return the first item in the list which is what I think you are wanting. Without knowing what the context.Users data type is, I can't tell you a better way to do this.

You could use something like:

user => user != null

But thats not really the best way to do it either.


修正了它。谢谢。



Fixed it up. Thank you.

public user GetUser(int userID)
        {
            using (var context = new iomniEntities())
            {
                user u = context.users.FirstOrDefault(user => user.userID == userID);

                return u;
            }
        }


这篇关于无法将lambda表达式转换为委托类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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