我想构建动态查询但未能获得所需的结果。 请参阅以下代码。 我尝试过使用两种不同的方法。
我想从“resultUsingLing”和“resultUsingDynamicLinq”获得相同的结果。 resultUsingDynamicLinq不返回任何值。
public class Test
{
public string Name { get; set; }
public string Address { get; set; }
}
public class Program
{
public static void Main()
{
List<Test> testList = new List<Test>()
{
new Test() { Address = "Address", Name = "Name" },
new Test() { Address = "Address1", Name = "Name1" },
new Test() { Address = "Address2", Name = "Name2" },
new Test() { Address = "Address3", Name = "Name3" },
new Test() { Address = "Address4", Name = "Name4" }
};
IQueryable<Test> queryableTestData = testList.AsQueryable<Test>();
var resultUsingLing= queryableTestData.Where(x => x.Address.Equals("Address1"));
string property = "Address";
string value = "Address1";
var type = typeof(Test);
var pe1 = Expression.Parameter(type, "p");
var propertyReference = Expression.Property(pe1, property);
var constantReference = Expression.Constant(value);
var resultUsingDynamicLinq= Expression.Lambda<Func<Test, bool>>
(Expression.Equal(propertyReference, constantReference),
new[] { pe1 }).Compile();
}
}
答案 0 :(得分:2)
那是因为你没有使用你在任何地方创建过的表达。
顺便说一下,你不应该编译它。编译为您提供Func<Test, bool>
,这将使您的Where
来电使用IEnumerable.Where
,而非IQueryable.Where
。
var expression = Expression.Lambda<Func<Test, bool>>
(Expression.Equal(propertyReference, constantReference),
new[] { pe1 });
var resultUsingDynamicLinq = queryableTestData.Where(expression).ToList();