C# 愚蠢的Linq查询?
我正在使用Sql server 2012,实体框架5.0 表客户:Id。。。 昵称(nvarchar(100))可以为空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
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));