简体   繁体   English

Linq to实体搜索算法

[英]Linq to Entities Search Algorithm

I'm implementing a search that will take six possible (but not required) user inputs and then try to match them to some entities. 我正在实现一个搜索,它将使用六个可能的(但不是必需的)用户输入,然后尝试将它们与某些实体匹配。

I think the issue I have come up against is that EF and SQL Server think of nulls as two very different things. 我认为我遇到的问题是EF和SQL Server将null视为两个非常不同的事物。

Idea: select an entity where columnA = (if columnA is null then columnA (or null) else searchTerm). 想法:选择一个实体,其中columnA =(如果columnA为null,则columnA(或null),否则为searchTerm)。 The search terms are a mix of ints and strings. 搜索词是整数和字符串的混合。

Some code: 一些代码:

entities= (from c in context.Entities
           where c.ColumnA == (searchTermA ?? v.ColumnA)
           where c.ColumnB == (searchTermB ?? v.ColumnB)
           select new
           {
               v.Property,
           }).ToList();

If all columns do not contain nulls, entities are returned. 如果所有列都不包含空值,则返回实体。 However, I do not get expected results if the column has nulls. 但是,如果列为空,则不会得到预期的结果。

How can I work around this? 我该如何解决?

Richard 理查德

Have the function accept a Predicate<T> and do the construction of the filter on the UI side. 让函数接受Predicate<T>并在UI端进行过滤器的构造。

See: http://msdn.microsoft.com/en-us/library/bfcke1bz.aspx 请参阅: http//msdn.microsoft.com/en-us/library/bfcke1bz.aspx

This is what i used to handle null values. 这就是我用来处理空值的东西。 It was the only way i could get the right results. 这是我可以获得正确结果的唯一方法。

((searchTermA.HasValue) ? (c.ColumnA == searchTermA) : true)

The easy way is this one: 一种简单的方法是:

var query = from c in context.Entities;

if  (searchTermA != null) {
    query = query.Where(c => c.ColumnA == searchTermA);
}

// Rest of your conditions defined in the same way.

var entities = query.Select(c => new { c.Property }).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM