Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 愚蠢的Linq查询?_C#_Linq - Fatal编程技术网

C# 愚蠢的Linq查询?

C# 愚蠢的Linq查询?,c#,linq,C#,Linq,我正在使用Sql server 2012,实体框架5.0 表客户:Id。。。 昵称(nvarchar(100))可以为空 Customer ICustomer service: Customer GetCustomer(Func<Customer, bool> pre); public Customer GetCustomer(Func<Customer, bool> pre) { return _customerRepo

我正在使用Sql server 2012,实体框架5.0

表客户:Id。。。 昵称(nvarchar(100))可以为空

Customer ICustomer service:    Customer GetCustomer(Func<Customer, bool> pre);


public Customer GetCustomer(Func<Customer, bool> pre)
        {
            return _customerRepository.Table.Where(pre).FirstOrDefault();
        }
它会生成一个错误:

异常详细信息:System.NullReferenceException:对象引用不存在 设置为对象的实例


当昵称包含空数据时

尝试使用
=

var customer = _customerService.GetCustomer(c => c.Nickname == "abc");
或者只是检查空值:

var customer = _customerService.GetCustomer(c => c.Nickname != null && c.Nickname.Equals("abc"));

是的,这是正确的,您不能对null调用方法。。。这样想:

当变量为null时,您将尝试执行以下操作:
null.Method()第一个示例将转换为SQL,该SQL将遵循数据库默认值进行null比较和排序,并且易于阅读(默认值将仅匹配昵称不为null的记录,并匹配“abc”,而不考虑Latin1_General_CI_AS的大小写)。
var customer = _customerService.GetCustomer(c => c.Nickname != null && c.Nickname.Equals("abc"));
var customer = _customerService.GetCustomer(c => "abc".Equals(c.Nickname));