所以,我想知道是否可以在C#中做下一件事:
我有一个DB模型--假设它是
public class Car {
public string Id {get;set;}
public string Name {get;set}
}
和
public DbSet<Car> Cars {get;set;}
我还有一个
public class CarDto {
public string Id {get;set;}
public string Name {get;set}
}
问题是--有可能用不同的IN对象动态构建linq WHERE表达式吗?
null
var select = new Func<CarDto, bool>(car => car.Name == "BMW");
// And somehow use this expression for other type Car
someDbContext.Cars.Where(select);
null
private static Expression<Func<T, bool>> BuildCondition<T>(string name)
{
var carParameter = Expression.Parameter(typeof(T), "car");
var propertyAccess = Expression.Property(carParameter, "Name");
var equalsTest = Expression.Equal(propertyAccess, Expression.Constant(name));
return Expression.Lambda<Func<T, bool>>(equalsTest, carParameter);
}
你会把它叫做:
someDbContext.Cars.Where(BuildCondition<CarDto>("BMW"));
我们通过使用
Expression<Func<CarDto, bool>> expr = x => x.Name == "BMW";
然后在调试器中检查