实体框架Linq是空的,不是空的问题 [英] Entity Framework Linq Is Null, Is Not Null Issue

查看:175
本文介绍了实体框架Linq是空的,不是空的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接收类别ID的方法,后跟两个可选的字符串参数,默认为null。

I have a method that receives a category id, followed by two optional string parameters that default to null.

我尝试使用其他问题的几个类似的答案SO,但sofar没有帮助。

I tried using a few similar answers from other questions on SO but sofar none have helped.

我正在尝试让linq到EF查询工作如下:

I am trying to get the linq to EF query to work as follows:

如果任一可选参数有一个值,请使用该值,否则使用Is Null。

If either optional parameter has a value, use the value otherwise use an Is Null.

如果两个可选参数都存在,则使用这些参数作为查询的一部分或任一个如果只提供eis。但是如果没有添加参数,只需使用类别ID。

If both optional parameters are present use these as part of the query or either one if only on eis supplied. But if no parmeters are added, just use the category id.

数据库中的两个可选参数都标记为可空。

Both optional parameters in the db are marked as nullable.

这是代码不起作用:

          from c in dtx.Categories
          where c.CategoryId == CatId
         && (string.IsNullOrEmpty(param1) ? c.Param1 == null : c.Param1 == param1)
         && (string.IsNullOrEmpty(param2) ? c.Param2 == null : c.Param2 == Param2)
        select c

尝试二:

          from c in dtx.Categories
          where c.CategoryId == CatId
          && (c.Param1 == null ? c.Param1 == null : c.Param1 == param1)
          && (c.Param2 == null ? c.Param2 == null : c.Param2 == param2)
          select c

不会抛出错误,但是两个查询总是返回零结果,除非这两个参数都存在。

No Errors are thrown, but both queries always return zero results unless both parameters are there.

我尝试过的一个帖子:
如何在实体框架中查询空值?

One of the posts I tried: How can i query for null values in entity framework?

推荐答案

从我可以看出,问题看起来像查询的条件没有正确写入。让我们检查一下附加的例子:

From what I can tell, the problem look like the condition of the query are not written correctly. Let check what will append with an example:

数据:

Id = 1, Param1 = null, Param2 = null
Id = 2, Param1 = 'a'   param2 = null
Id = 3, Param1 = null, Param2 = 'b'
Id = 4, Param1 = 'a'   param2 = 'c'

使用当前查询和其他解决方案建议你只能得到Id 1.
你的条件是说:如果Param1是Null和c.Param1(存储的值)为空OR c.Param1等于Param1值。

With the current query and the other solution proposed you will only get the Id 1. Your condition are saying : If the Param1 Is Null and c.Param1 (the stored value) Is null OR c.Param1 Is Equal to Param1 value.

您需要的条件是:如果Param1为空或c.Param1等于Param1值。

What you need is a condition that says : If Param1 Is Null OR c.Param1 Is Equal to Param1 value.

如果您使用这个查询,你将永远得到你的结果。

If you use this query, you will always get the your result.

from c in dtx.Categories
where c.CategoryId == CatId
    && (string.IsNullOrEmpty(param1) || c.Param1 == param1)
    && (string.IsNullOrEmpty(param2) || c.Param2 == param2)
select c

这篇关于实体框架Linq是空的,不是空的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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