[英]How to pass a Lambda Expression as method parameter with EF
How do I pass an EF expression as a method parameter?如何将 EF 表达式作为方法参数传递?
To illustrate my question I have created a pseudo code example:为了说明我的问题,我创建了一个伪代码示例:
The first example is my method today.第一个例子是我今天的方法。 The example utilizes EF and a Fancy Retry Logic.
该示例使用 EF 和 Fancy Retry Logic。 What I need to do is to encapsulate the Fancy Retry Logic so that it becomes more generic and does not duplicate.
我需要做的是封装Fancy Retry Logic,让它变得更通用,不会重复。
In the second example is how I want it to be, with a helper method that accepts the EF expression as a parameter.在第二个示例中,它是我希望的样子,使用接受 EF 表达式作为参数的辅助方法。
This would be a trivial thing to do with SQL, but I want to do it with EF so that I can benefit from the strongly typed objects.这对 SQL 来说是一件微不足道的事情,但我想用 EF 来做,这样我就可以从强类型对象中受益。
First Example:第一个例子:
public static User GetUser(String userEmail)
{
using (MyEntities dataModel = new MyEntities ())
{
var query = FancyRetryLogic(() =>
{
(dataModel.Users.FirstOrDefault<User>(x => x.UserEmail == userEmail)));
});
return query;
}
}
Second Example:第二个例子:
T RetryHelper<T>(Expression<Func<T, TValue>> expression)
{
using (MyEntities dataModel = new (MyEntities ())
{
var query = FancyRetryLogic(() =>
{
return dataModel.expression
});
}
}
public User GetUser(String userEmail)
{
return RetryHelper<User>(<User>.FirstOrDefault<User>(x => x.UserEmail == userEmail))
}
Maybe something like this?也许是这样的?
public TValue RetryHelper<T, TValue>(Func<ObjectSet<T>, TValue> func)
where T : class
{
using (MyEntities dataModel = new MyEntities())
{
var entitySet = dataModel.CreateObjectSet<T>();
return FancyRetryLogic(() =>
{
return func(entitySet);
});
}
}
public User GetUser(String userEmail)
{
return RetryHelper<User, User>(u => u.FirstOrDefault(x => x.UserEmail == userEmail));
}
Just to post what we discussed already...只是为了发布我们已经讨论过的内容......
Here is a link that might help you, I think it has something similar to what you need.这是一个可能对您有帮助的链接,我认为它与您需要的东西相似。
Using AsQueryable With Linq To Objects And Linq To SQL 将 AsQueryable 与 Linq 结合使用到对象,并将 Linq 与 SQL 结合使用
How do I cache an IQueryable object? 如何缓存 IQueryable object?
I've seen better examples but I don't have them handy, basically as I mentioned you can use that to keep your query in a form so that you can further filter, change until the very last moment when you know all is done and can actually realize and enumerate the query.我见过更好的例子,但我手边没有,基本上就像我提到的那样,你可以使用它来保持你的查询形式,这样你就可以进一步过滤,改变直到你知道一切都完成的最后一刻实际上可以实现和枚举查询。
hope it helps希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.