我有一个大项目,我有几十个linq语句,我正在寻找一个匹配的记录,通过检查几个字段,看看它们是否匹配或两个字段和比较字段为空。
var testRecord = new { firstField = "bob", secondField = (string)null, thirdField = "ross" };
var matchRecord = dataContext.RecordsTable.FirstOrDefault(vi =>
(vi.first == testRecord.firstField || ((vi.first == null || vi.first == string.Empty) && testRecord.firstField == null))
&& (vi.second == testRecord.secondField || ((vi.second == null || vi.second == string.Empty) && testRecord.secondField == null))
&& (vi.third == testRecord.thirdField || ((vi.third == null || vi.third == string.Empty) && testRecord.thirdField == null)));
//do stuff with matchRecord
理想情况下,我会将所有重复的代码(在我正在工作的系统中使用大约50次)替换为以下内容
Expression<Func<string, string, bool>> MatchesOrBothNull = (infoItem, matchItem) => (
infoItem == matchItem || ((infoItem == null || infoItem == string.Empty) && matchItem == null));
var matchRecord = dataContext.RecordsTable.FirstOrDefault(vi =>
MatchesOrBothNull(vi.first, testRecord.firstField)
&& MatchesOrBothNull(vi.second, testRecord.secondField)
&& MatchesOrBothNull(vi.third, testRecord.thirdField));
//do stuff with matchRecord
我的问题是双重的:首先,是否有一个匹配的或两个null函数已经可用?(我找过了,运气不好)。第二,上面的代码块可以编译,但是会抛出一个"不支持转换"到sql"错误,有没有办法在where子句中有一个函数?我知道有一个转换,因为如果我不把它拉入函数中,它是有效的。怎么翻译呢?
首先,您可以使用单个代码检查字符串是否为空或空,称为:String.IsNullOrEmpty(vi.first)
。你需要一个像这样的方法:
public bool MatchesOrBothNull(string first,string second){
if(first==second||String.IsNullOrEmpty(first)||String.IsNullOrEmpty(second))
return true;
else return false;
}
可以用在where子句
var matchRecord = dataContext.RecordsTable.Where(vi =>
MatchesOrBothNull(vi.first, testRecord.firstField)
&& MatchesOrBothNull(vi.second, testRecord.secondField)
&& MatchesOrBothNull(vi.third, testRecord.thirdField)
).FirstOrDefault();