LINQ to SQL:where 条件中的子过滤器
这个问题可能已经在某个地方得到了回答(如果是这样,我很想有链接!)。但由于我不知道我正在尝试执行什么类型的 linq 查询,因此我无法找到任何可以帮助我的内容。
我已经有了一个非常简单的查询设置来获取 DomainSequences 类型的所有记录。
var query = db.DomainSequences;
存在不同类型的域序列。我想得到他们全部。但是,对于 DomainType 属性等于“AT”的记录,那么我只想返回其中一些“AT”记录(即,对这些记录执行 where 子句以过滤“AT”记录,但仍想返回所有非“AT”记录。
更简单地说,我想获取所有 DomainSequence 记录,但对于具有 DomainType ==“AT”的记录,则仅在满足某些条件时才返回这些记录
。通过做类似的事情来做到这一点:
query.Where(x => x.DomainType != "AT" || (x.DomainType == "AT" && AT conditions....));
我认为这应该可行,但当我必须在其他列上进行子过滤器时,问题就出现了,然后它很快就开始变得更加混乱和复杂,
理想情况下,我想做一些类似的事情,
query.Where(x => x.DomainType == "AT" || x.DomainType == "KS")
.WhereIf(y => y.DomainType == "AT" then apply filter on those)
.WhereIf(z => z.DomainType == "KS" then apply filter to these);
我不确定是否有办法做到。 LINQ 或 SQL 中的这种类型的子过滤器(尽管我想象有)。关于如何相对干净地完成此操作有什么建议吗?
谢谢!
This question may have been answered somewhere (and if so I would love to have the link!). But since I don't know what type of linq query I'm trying to do, I haven't been able to find anything to help me.
I already have a very simple query setup to get all records of type DomainSequences.
var query = db.DomainSequences;
There are different types of domain sequences. I want to get all of them. However, for records that have a DomainType attribute equal to 'AT', then I only want to return some of those of 'AT' records (ie. do a where clause on those to filter the 'AT' records but still want to return all non 'AT' records.
More simply put, I want to get all DomainSequence records, but for the records that have a DomainType == "AT", then return those only if they meet certain conditions.
I can think of a way of doing it by doing something like:
query.Where(x => x.DomainType != "AT" || (x.DomainType == "AT" && AT conditions....));
I think this should work but the problem comes when I have to do subfilters on other columns and then it starts to get messier and complicated very quickly.
Ideally, I would like to do something like
query.Where(x => x.DomainType == "AT" || x.DomainType == "KS")
.WhereIf(y => y.DomainType == "AT" then apply filter on those)
.WhereIf(z => z.DomainType == "KS" then apply filter to these);
I'm not sure if there is a way to do this type of subfilter in LINQ or in SQL (though I imagine there is). Any suggestions on how this could be done relatively cleanly?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它实际上与您用 SQL 编写的内容没有什么不同。事实上,如果您尝试查询表达式语法方法,您可能会发现该特定连接更容易建立。
这很好地映射到您可能期望编写的 SQL
当然,您可以使用 lambda 将其保留在流畅的扩展方法语法中,当然,它只是一个
.Where(...)
调用, 毕竟。It's really not all that different than what you might write in SQL. In fact, if you would try the query expression syntax approach, you might find that particular connection easier to make.
That maps nicely to the SQL you might expect to write
You could, of course, keep it in the fluent extension method syntax using lambdas, of course, it's just a single
.Where(...)
invocation, after all.