我是实体框架的新手,我正在努力解决我希望的基本问题。我的代码在这里:
Dim accounts As List(Of STUDENT) =
(From a In SA.STUDENTs
Where (a.MATRIC_NO.Contains(matric) And a.FIRST_NAME.Contains(firstName) And a.MIDDLE_NAMES.Contains(middleName) And a.SURNAME.Contains(lastName) And a.PREFERRED_NAME.Contains(preferredName))
Select a).ToList
查询运行正常,直到数据库中的某个搜索字段为NULL。例如,如果在搜索界面中输入了matric编号但中间名留空,则如果数据库中的中间名为NULL,则查询将不返回任何记录。如果中间名是数据库中的空格,则它将返回记录。
任何人都可以提供任何指示吗?
非常感谢!
答案 0 :(得分:0)
您可以在查询中添加额外的检查。例如:
public function filterList(IEnumerable list, string name)
{
var filtered_list = list.Where(x=> x.Name.Contains(name) || string.IsNullorWhitespace(name)).ToList();
return filtered_list;
}
因此,您可以看到,如果name
变量为空,则所有元素都将返回true,因此所有元素都将返回(未应用实际过滤器)。
基本上,您可以从
更改所有过滤器something.Contains(anotherthing)
到
something.Contains(anotherthing) || string.IsnullOrWhitespace(anotherthing)
答案 1 :(得分:0)
(From a In SA.STUDENTs
Where isnull(a.MATRIC_NO.Contains(matric) And a.FIRST_NAME.Contains(firstName) And a.MIDDLE_NAMES.Contains(middleName) And a.SURNAME.Contains(lastName) And a.PREFERRED_NAME.Contains(preferredName))
Select a).ToList
像这样`:select * from table where status = is null(@ statusid,status_id)
答案 2 :(得分:0)
试试这个..
Dim get_rmf_2 = From rmf In t_rmf _
Where Not IsDBNull(rmf!NIVP) AndAlso rmf!NIVP = nivp_rap
这是在VB中我觉得这很好用
答案 3 :(得分:0)
我设法使用不同的方法来解决这个问题。如果没有为特定字段输入值,请将其保留在查询之外。我使用谓词完成了这个,如下所示:
'create the base query
Dim accounts =
(From a In SA.STUDENTs
Select a)
'create predicates for each condition required in the query
If matric <> "" Then
accounts = accounts.Where(Function(m) m.MATRIC_NO.Contains(matric))
End If
If firstName <> "" Then
accounts = accounts.Where(Function(f) f.FIRST_NAME.Contains(firstName))
End If
If middleName <> "" Then
accounts = accounts.Where(Function(mn) mn.MIDDLE_NAMES.Contains(middleName))
End If
If lastName <> "" Then
accounts = accounts.Where(Function(l) l.SURNAME.Contains(lastName))
End If
If preferredName <> "" Then
accounts = accounts.Where(Function(p) p.PREFERRED_NAME.Contains(preferredName))
End If
'execute the query
Dim accountlist = accounts.ToList
'return the results
Return accountlist
如果有人可以看到任何错误,或任何我不知道的问题,请告诉我!我对LINQ to Entities和LINQ一般都很新!