我已经看过围绕这个的其他问题,我无法弄清楚如何将答案应用到我的特定情况.假设您有几个看起来像这样的模型:
public class Person
{
public int PersonId { get; set; }
}
public class Business
{
public int BusinessId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我希望能够编写几个不同的泛型方法:一个使用提供的Lambda获取模型,可能看起来像这样:
GetWhere(p => p.PersonId == 1)
Run Code Online (Sandbox Code Playgroud)
一个使用唯一键获取模型 - 为了使其灵活,我希望能够使用Lambda指定唯一键:
GetByUniqueKey(p => p.PersonId, 1)
Run Code Online (Sandbox Code Playgroud)
要么
GetByUniqueKey(b => b.BusinessId, 1)
Run Code Online (Sandbox Code Playgroud)
理想情况下GetByUniqueKey,只需要一个简化方法来构建要发送的表达式GetWhere,然后返回FirstOrDefault()结果.但这样做的逻辑完全逃避了我.我想做的事:
public IEnumerable<TModel> GetWhere(Expression<Func<TModel, bool>> whereExpression)
{
// Get from DB using expression provided
}
public TModel GetByUniqueKey<TUniqueKey>(
Expression<Func<TModel, TUniqueKey>> uniqueKeyProperty,
TUniqueKey value)
{
return GetWhere(m => uniqueKeyProperty(m) == value).FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)
所以我想获取uniqueKeyProperty表达式,以某种方式在提供的参数上调用它来获取属性,然后在表达式中使用该属性whereExpression.
关于重复问题的说明: 我知道这看起来像是其他类似问题的重复,但请注意我已阅读过这些问题而我无法弄清楚如何将这些答案应用于我的具体用例.
对评论的一些澄清:
简而言之,我想做以下事情:
我想取表达式p => p.PersonId和值1,并生成一个whereExpression看起来像这样的p => p.PersonId == 1.(谢谢@Rob)
您可以从键选择器和提供的值构建新表达式,如下所示:
public TModel GetByUniqueKey<TUniqueKey>(
Expression<Func<TModel, TUniqueKey>> uniqueKeySelector,
TUniqueKey value)
{
return GetWhere(Expression.Lambda<Func<TModel,bool>>(
Expression.MakeBinary(
ExpressionType.Equal,
uniqueKeySelector.Body,
Expression.Constant(value, typeof(TUniqueKey))),
uniqueKeySelector.Parameters));
}
Run Code Online (Sandbox Code Playgroud)
对于按 ID 查询,我不会采用这种方法。查看Expression 类上的其他静态方法。