我有以下代码:
public Expression FilterString(string property, string value, ParameterExpression parameter)
{
//Create Message MemberExpression from parameter and properted eg/Message.Body
var getname = Expression.Property(parameter, property);
//Create expression for Not IsNullOrEmpty
var isnullorempty = Expression.Not(Expression.Call(typeof(string), "IsNullOrEmpty", null, getname));
//Create expression for member property equal to value eg/Message.Body = "hi"
var toLower = Expression.Call(getname,
typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));
var compare = Expression.Equal(toLower, Expression.Constant(value));
//Create expression combining Not IsNullOrEmpty AND Equal To
var condition = Expression.And(isnullorempty, compare);
return condition;
}
如果我运行下面的测试,我会得到一个NullReferenceException
,我假设因为某些项目的主体为空,但这正是Expression
应该测试的。
private IEnumerable<Message> GetMessages()
{
var list = new List<Message>();
var message = new Message() { Body = null, Properties = new Collection<MessageProperty>() };
list.Add(message);
message = new Message() { Body = "", Properties = new Collection<MessageProperty>() };
list.Add(message);
message = new Message() { Body = "Hello Everybody", Properties = new Collection<MessageProperty>() };
list.Add(message);
message = new Message() { Flag = 1, Properties = new Collection<MessageProperty>() };
list.Add(message);
message = new Message() { ChannelInt = 1, Properties = new Collection<MessageProperty>() };
list.Add(message);
message = new Message() { Properties = new Collection<MessageProperty>(new[] { new MessageProperty() { Key = "Gender", Value = "male" } }) };
list.Add(message);
return list;
}
[Theory]
[InlineData("Hello Everybody")]
[InlineData("hello everybody")]
public void FilterString_NullAndEmptyMessages_Removed(string searchTerm)
{
var messageList = GetMessages();
var parameter = Expression.Parameter(typeof(Message), "message");
var equalToFilterType = new EqualToFilterType();
var filter = equalToFilterType.FilterString("Body", searchTerm, parameter);
var lambda = Expression.Lambda(filter, parameter);
//******EXCEPTION*******//
var result = messageList.AsQueryable().Where((Expression<Func<Message, bool>>)lambda).ToList();
Assert.Equal(1, result.Count);
}
有什么想法可以让我通过这个测试吗?(顺便说一句,我的表达式代码也将用于命中 SQL Server)